g0dst3r
g0dst3r

Reputation: 69

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 :)

Upvotes: 0

Views: 6152

Answers (2)

5rod
5rod

Reputation: 458

@Countour-Integral's answer is great, but here's another solution: wait until the key stops being pressed directly inside the function by using keyboard. This way, you can omit the global variables:

from pynput.keyboard import Key, Listener
import keyboard

def on_press(key):
    print('f1 pressed')
    if key == Key.f1:
        while True:
            if not keyboard.is_pressed('f1'):
                break

def on_release(key):
    if key == Key.f1:
        print('f1 released')

with Listener(on_press=on_press) as listener:
    listener.join()

Upvotes: 0

Countour-Integral
Countour-Integral

Reputation: 1154

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) 

Upvotes: 2

Related Questions