0
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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.