3 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
import keyboard
running = True
display = True
block = False
while running:
if keyboard.is_pressed("k"):
if block == False:
display = not display
block = True
else:
block = False
if display:
print("hello")
else:
print("not")

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
也許是這樣的:
import keyboard
running = True
stop = False
while !stop:
if keyboard.is_pressed("k"):
running = !running # Stops "hello" while
if keyboard.is_pressed("q"):
stop = !stop # Stops general while
if running:
print("hello")

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以為按鍵使用一個(gè)處理程序,它設(shè)置一個(gè)事件,主線程可以定期測(cè)試該事件,并在需要時(shí)等待。
(請(qǐng)注意,這里有兩種類型的事件,按鍵事件和 的設(shè)置running,因此不要將它們混淆。)
from threading import Event
from time import sleep
import keyboard
hotkey = 'k'
running = Event()
running.set() # at the start, it is running
def handle_key_event(event):
if event.event_type == 'down':
# toggle value of 'running'
if running.is_set():
running.clear()
else:
running.set()
# make it so that handle_key_event is called when k is pressed; this will
# be in a separate thread from the main execution
keyboard.hook_key(hotkey, handle_key_event)
while True:
if not running.is_set():
running.wait() # wait until running is set
sleep(0.1)
print('hello')
添加回答
舉報(bào)