4 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個贊
您可以使用模塊中的事件處理程序來實(shí)現(xiàn)所需的結(jié)果。keyboard
一個這樣的處理程序是keyboard.on_press(回調(diào),suppress=False):它為每個事件調(diào)用一個回調(diào)。您可以在鍵盤文檔中了解更多信息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貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個贊
對于將來可能需要它的人,您可以使用它基本上等到按鍵被按下keyboard.wait()
keyboard.wait("o")
print("you pressed the letter o")
請記住,它會阻止代碼執(zhí)行。如果你想運(yùn)行代碼,如果鍵沒有被按下,我建議做
if keyboard.is_pressed("0"):
#do stuff
else:
#do other stuff

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個贊
沒關(guān)系,另一個答案使用幾乎相同的方法
這是我可以想到的,使用相同的“鍵盤”模塊,請參閱下面的代碼內(nèi)注釋
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貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超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()
這將與主線程中的任何內(nèi)容并行運(yùn)行,并且專門用于基本上偵聽該按鍵。
添加回答
舉報