Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65890326/keyboard-press-detection-with-pynput

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...