每当我按下键时,我如何才能将其递增和打印,而不仅仅是一次?
使用以下程序,每当我按“ A”键时,键>
变量 1 。问题是,如果我不立即放任键,键>键>变量将继续通过
1
递增。
每当我按键以忽略保留方面时,我如何才能将其递增(和打印)?
import keyboard
keypresses = 0
while True:
if keyboard.is_pressed("a"):
keypresses = keypresses +1
print(keypresses)
print("A Key Pressed")
break
With the below program, whenever I press the "a" key, the keypresses
variable increments by 1
. The problem is, if I don't immediately let go fo the key, the keypresses
variable continues to increment by 1
.
How can I get it to increment (and print) whenever I press the key, ignoring the hold aspect?
import keyboard
keypresses = 0
while True:
if keyboard.is_pressed("a"):
keypresses = keypresses +1
print(keypresses)
print("A Key Pressed")
break
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我了解您想要它,以便仅一旦(不是无限期)按下打印,并且只要
a
键再次释放并再次按下,它就会再次打印。定义一个变量,
按
,以获取是否仍在按下或发布键:I understand that you want it so that pressing and holding only prints once (not indefinitely), and it will print again as long as the
a
key is released and pressed again.Define a variable,
pressing
, to get if the key is still being pressed, or released:如果您删除这样的休息语句:
这是不起作用的,并且运行它时,它会立即完成。
因为
键盘.is_pressed
仅检测现在正是由于此事,
如果您在Windows中,这会导致CPU太多,您可以将
msvcrt
代替:-)if you remove the break statement like this:
this does not work, and when you run it, it is instantly finished the while cycle.
because the
keyboard.is_pressed
only detect nowand precisely because of this, which caused too many cpu
if you are in windows , you can use
msvcrt
to instead :-)我将删除
break
语句。在 python docs 在/
循环时,将最内向的
退出,在您的情况下,该循环将是
I'd remove the
break
statement.On the Python docs you can see that
break
exits the innermostfor
/while
loop, in your case the that loop would be the