我目前正在寻找一个能够检测/监控键盘的库。
我的意图是在按住某个按键时检测到,并且在该情况发生时应该执行某些操作。
大多数SO帖子建议使用pygame,但我觉得这对于这个简单的任务来说有些过度。我也尝试过使用pynput
,但结果仅仅能检测到一次按键而不是连续按下。
有什么建议可以让这个while循环检测到按键被按下/按住...
我的while循环尝试:
from pynput import keyboard
def on_press(key):
while key == keyboard.Key.cmd_l:
try:
print('- Started recording -'.format(key))
except IOError:
print "Error"
else:
print('incorrect character {0}, press cmd_l'.format(key))
def on_release(key):
print('{0} released'.format(key))
if key == keyboard.Key.cmd_l:
print('{0} stop'.format(key))
keyboard.Listener.stop
return False
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
这个 while 解决方案会使其陷入 while 循环中,无法跳出。
while True:
和try
块中? - user8253094while True: try:
吗?我试过了,但结果却一直停留在那个 while 循环里面,无法跳出。 - Mama