Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to check if ANY key is pressed, is this possible?

How do I check if ANY key is pressed?

this is how I know to detect one key:

import keyboard  # using module keyboard
while True:  # making a loop
    if keyboard.is_pressed('a'):  # if key 'q' is pressed
        print('You Pressed A Key!')
        break  # finishing the loop 

How do I check if any key (not just letters) is pressed? For example, if someone presses the spacebar it works, the same for numbers and function keys, etc.

like image 404
Keyboard's_Slave Avatar asked Dec 06 '25 17:12

Keyboard's_Slave


2 Answers

while True:
    # Wait for the next event.
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN:
        print(event.name) # to check key name

Press any key and get the key name.

like image 50
sifat Avatar answered Dec 08 '25 07:12

sifat


it can be done using the msvcrt module as the following:

import msvcrt

while True:
    if msvcrt.kbhit():
        key = msvcrt.getch()
        break

or the keyboard, although i am not sure of how of a good practice this code is:

import keyboard

while True:
    try:
        print(keyboard.read_key())
        break
    except:
        pass

if this is bad practice please informe me in the coments so i can mark it as unfavored

thankyou.

like image 43
Hannon qaoud Avatar answered Dec 08 '25 07:12

Hannon qaoud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!