Is there a way to limit Python's keyboard.add_hotkey() to trigger only once per keystroke?

33 views Asked by At
import keyboard
def on_c_pressed():
    print("C key was pressed")

keyboard.add_hotkey('c', on_c_pressed)

Current situation is that it fires rapidly as the keystroke is actuated and being released.

One solution is to keep track of a global variable flag and have on_c_pressed() and on_c_released but that seems a little messy. Do any of you know a cleaner way or an alternative library that detects when I press a key state once per press?

1

There are 1 answers

0
5rod On

You can just wait for the key to be released:

import keyboard

def c_press():
    print('c was pressed')
    while True:
        if not keyboard.is_pressed('c'):
            break

keyboard.add_hotkey('c', c_press)

We wait for 'c' to stop being pressed in this method. For other modules, you might want to take a look at pynput.