pythonkeyboardpynput

Keyboard Press Detection with pynput


from pynput import keyboard 

def on_press(key): 
    print('Key %s pressed' % key) 

def on_release(key): 
    print('Key %s released' %key) 

with keyboard.Listener( on_press=on_press, on_release=on_release) as listener: 
    listener.join()

if i keep pressing the F1 button and release, it says

Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 released

if i keep pressing the F1 button and release,i want it to work like below

Key Key.f1 pressed
Key Key.f1 released

Please help me :)


Solution

  • pressed = False
    
    def on_press(key): 
        global pressed
        if not pressed and key == keyboard.Key.f1: # only if key is not held
            print('Key %s pressed' % key) 
            pressed = True # key is held
    
    def on_release(key):
        global pressed 
        if key == keyboard.Key.f1:
            print('Key %s released' %key) 
            pressed = False # key is released
    

    Code is pretty self explanatory, you just provide a boolean pressed that whenever you press the F1 key it is True and whenever you release it, it is False. If press is False you just ignore the on_press "signal".

    if you want to achieve this with every key you'll have to store the state of every key in a dictionary (or as similar object).

    pressed = {}
    
    def on_press(key): 
        if key not in pressed: # Key was never pressed before
            pressed[key] = False
        
        if not pressed[key]: # Same logic
            pressed[key] = True
            print('Key %s pressed' % key) 
    
    def on_release(key):  # Same logic
        pressed[key] = False
        print('Key %s released' %key)