How can i get it to increment and print whenever i press the key, not just once?

312 Views Asked by At

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
3

There are 3 best solutions below

0
On

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:
0
On

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
0
On

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 :-)