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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…