'How can i get it to increment and print whenever i press the key, not just once?
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
Solution 1:[1]
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:
import keyboard
keypresses = 0
pressing = False
while True:
if keyboard.is_pressed("a"):
if not pressing:
pressing = True
keypresses = keypresses +1
print(keypresses)
print("A Key Pressed")
else:
pressing = False
Solution 2:[2]
if you remove the break statement like this:
import keyboard
keypresses = 0
while True:
if keyboard.is_pressed("a"):
keypresses = keypresses +1
print(keypresses)
print("A Key Pressed")
break
this does not work, and when you run it, it is instantly finished the while cycle.
because the keyboard.is_pressed
only detect now
and precisely because of this, which caused too many cpu
if you are in windows , you can use msvcrt
to instead :-)
Solution 3:[3]
I'd remove the break
statement.
On the Python docs you can see that break
exits the innermost for
/while
loop, in your case the that loop would be the
while True:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ann Zen |
Solution 2 | zephms |
Solution 3 | Liam |