How to stop output spamming when your using this keyboard.is_pressed() function in a while True loop

52 Views Asked by At

I want to create a python code where if I press the number 0, the number 0 gets returned as output. But when I use the keyboard.is_pressed() module it keeps spamming, I was wondering if it's possible to stop it without using time.sleep() or quit().

CODE:

import keyboard

while True:
    if keyboard.is_pressed('0'):
        print('0')

OUTPUT:

0
0
0
0
0
0
0...
2

There are 2 best solutions below

0
sashkins On

You need to consider the state of the button, and print '0' only if the key is pressed at the moment.
The below code will print '0' only when it is pressed.

import keyboard

was_key_pressed = False
while True:
    is_key_pressed_now = keyboard.is_pressed('0')

    if is_key_pressed_now and not was_key_pressed:
        print('0')

    was_key_pressed = is_key_pressed_now
0
Steven Rumbalski On

The keyboard docs have the answer:

Repeatedly waiting for a key press

import keyboard

# Don't do this!
#
#while True:
#    if keyboard.is_pressed('space'):
#        print('space was pressed!')
#
# This will use 100% of your CPU and print the message many times.

# Do this instead
while True:
    keyboard.wait('space')
    print('space was pressed! Waiting on it again...')