Once I press "q" it prints this text many times. I want to print it once.
import keyboard
while True:
try:
if keyboard.is_pressed("q"):
print('q pressed')
except:
break
CodePudding user response:
Your current code is constantly repeating check until q
is pressed, which is not cpu efficient, and also once the q
is pressed is_pressed
will always be True
- it does not automatically reset.
There is a good example of what you want in the docs. Do something like this:
keyboard.wait('q')
print('q pressed, continue...')
Note that this will block execution until q
is pressed, and will continue after that. If you want to repeat process, simply put it inside while loop:
while True
keyboard.wait('q')
print('q pressed, waiting on it again...')
CodePudding user response:
Hi you need to break in your try clause after printing in order for loop to end, just like you did in except;
while True:
try:
if keyboard.is_pressed("q"):
print('q pressed')
break
except:
break
CodePudding user response:
The reason your code repeats is that you do not check for when q is released. this causes the condition if keyboard.is_pressed("q")
to run multiple times
to stop this. you need to check for when q
is released
for example
import keyboard
is_pressed = False
while True:
try:
if keyboard.is_pressed("q") && not is_pressed:
print('q pressed')
is_pressed = True:
if not keyboard.is_pressed("q"):
is_pressed = False
except:
break