2

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.

3 Answers3

3
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.

sifat
  • 353
  • 1
  • 8
2

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.

Hannon qaoud
  • 785
  • 2
  • 21
0

Correct solution in Windows is to use msvcrt Please check thread here: How to detect key presses?

I think somehow should be possible also with builtin input() command.

Have a nice day!

Marco smdm
  • 1,020
  • 1
  • 15
  • 25