You have to compare
key.char == '7'
but it gives error when key
doesn't have .char
- i.e. Ctrl
, Alt
, Shift
, etc. and even Space
- so safer is to compare
key == KeyCode.from_char('7')
from pynput.keyboard import Listener, Key, KeyCode
def on_press(key):
try:
print('from_char:', key == KeyCode.from_char('7'))
print('key.char :', key.char == '7')
except Exception as ex:
print('Error:', ex)
def on_release(key):
#print('{0} released'.format(key))
if key == Key.esc:
# Stop listener
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
EDIT:
from pynput.keyboard import Listener, Key, KeyCode
#allowed = [KeyCode.from_char('7'), KeyCode.from_char('9')]
#allowed = [KeyCode.from_char(char) for char in ['7','9','1','3','4','5','6','q','w','e','z']]
allowed = [KeyCode.from_char(char) for char in '7913456qwez']
def on_press(key):
try:
print('allowed:', key in allowed)
except Exception as ex:
print('Error:', ex)
def on_release(key):
#print('{0} released'.format(key))
if key == Key.esc:
# Stop listener
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…