Detecting keypresses in Python

53 Views Asked by At

I'm trying to detect a keypress (for example Space) in Python. Everyone online is referring to the module 'Keyboard'. I've tried to use this, but it will not work. I did install the package and I'm using import keyboard in my first line of code.

I'm using Repl.it to write my code, I don't know if this makes a difference.

Any help is welcome!

This is my code:

import keyboard

keyboard.wait('p')
print('You pressed p')

I'm trying to detect when the user is pressing a certain key. Once the key is pressed, the code continues.

1

There are 1 best solutions below

0
Marco Parola On

This piece of code does what you ask

import keyboard

def wait_for_keypress():
    print("Press any key to continue...")
    event = keyboard.read_event(suppress=True)  # Wait for a key press
    if event.event_type == keyboard.KEY_DOWN:
        print(f"You pressed the key: {event.name}")

wait_for_keypress()

print("Program continues...")

ensure that keyword module is installed, othewise install it via pip