4 回答

TA贡献1840条经验 获得超5个赞
您可以使用模块中的事件处理程序来实现所需的结果。keyboard
一个这样的处理程序是keyboard.on_press(回调,suppress=False):它为每个事件调用一个回调。您可以在键盘文档中了解更多信息key_down
以下是您可以尝试的代码:
import keyboard # using module keyboard
import time
stop = False
def onkeypress(event):
global stop
if event.name == 'q':
stop = True
# ---------> hook event handler
keyboard.on_press(onkeypress)
# --------->
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
print("sleeping")
time.sleep(5)
print("slept")
if stop: # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
print("#######")
break # if user pressed a key other than the given key the loop will break

TA贡献1784条经验 获得超2个赞
对于将来可能需要它的人,您可以使用它基本上等到按键被按下keyboard.wait()
keyboard.wait("o")
print("you pressed the letter o")
请记住,它会阻止代码执行。如果你想运行代码,如果键没有被按下,我建议做
if keyboard.is_pressed("0"):
#do stuff
else:
#do other stuff

TA贡献1836条经验 获得超5个赞
没关系,另一个答案使用几乎相同的方法
这是我可以想到的,使用相同的“键盘”模块,请参阅下面的代码内注释
import keyboard, time
from queue import Queue
# keyboard keypress callback
def on_keypress(e):
keys_queue.put(e.name)
# tell keyboard module to tell us about keypresses via callback
# this callback happens on a separate thread
keys_queue = Queue()
keyboard.on_press(on_keypress)
try:
# run the main loop until some key is in the queue
while keys_queue.empty():
print("sleeping")
time.sleep(5)
print("slept")
# check if its the right key
if keys_queue.get()!='q':
raise Exception("terminated by bad key")
# still here? good, this means we've been stoped by the right key
print("terminated by correct key")
except:
# well, you can
print("#######")
finally:
# stop receiving the callback at this point
keyboard.unhook_all()

TA贡献1898条经验 获得超8个赞
您可以使用线程
import threading
class KeyboardEvent(threading.Thread):
def run(self):
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
keyread = KeyboardEvent()
keyread.start()
这将与主线程中的任何内容并行运行,并且专门用于基本上侦听该按键。
添加回答
举报