按下一个键时仅增加一个 [英] Increase just by one when a key is pressed
问题描述
无论我按下多长时间,我想在按下键"s"时仅将变量"shot_pressed"增加一.但是结果是变量不断增加.我按下的时间越长,变量的值越大.下面是我的代码的一部分.
I want to increase the variable "shot_pressed" just by one when the key "s" is pressed no matter how long I pressed. But the result is that the variable keeps on increasing. The longer I pressed, the bigger the value of the variable. Below is a part of my code.
import keyboard
shot_pressed = 0
if keyboard.is_pressed('s'):
shot_pressed += 1
推荐答案
首先,您看起来像使用https://pypi.python.org/pypi/keyboard
First of all looks like you use https://pypi.python.org/pypi/keyboard
第二,我认为您的代码不像您上面编写的那样,而是像
Second, I assume your code is not like you wrote above but like
import keyboard
shot_pressed = 0
while True:
if keyboard.is_pressed('s'):
shot_pressed += 1
print("shot_pressed %d times"%shot_pressed)
如果是,这是问题的核心:按下键时,is_pressed始终为True.因此 if
条件将为True,而 while
条件将重复多次.
If yes, here is the core of the problem: is_pressed will be always True, while key is pressed. So if
condition will be True and while
will repeat it many times.
有两种处理方法.
1)使用相同的方法,但是检查这是否是is_pressed的第一个时刻,因此引入 was_pressed
变量:
1) Use the same method, but check if this is the first is_pressed moment, so inroduce was_pressed
variable:
import keyboard
shot_pressed = 0
was_pressed = False
while True:
if keyboard.is_pressed('s'):
if not was_pressed:
shot_pressed += 1
print("shot_pressed %d times"%shot_pressed)
was_pressed = True
else:
was_pressed = False
2)更好地使用该库.您可以设置一个钩子,这样在按键时将调用您的函数(一次按一次).因此,代码将如下所示:
2) Better use the library. You can set a hook, so on key pressed your function will be called (only once for one press). So the code will look like this:
import keyboard
shot_pressed = 0
def on_press_reaction(event):
global shot_pressed
if event.name == 's':
shot_pressed += 1
print("shot_pressed %d times"%shot_pressed)
keyboard.on_press(on_press_reaction)
while True:
pass
这篇关于按下一个键时仅增加一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!