3 回答

TA贡献1786条经验 获得超13个赞
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贡献1891条经验 获得超3个赞
也许是这样的:
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贡献1796条经验 获得超10个赞
您可以为按键使用一个处理程序,它设置一个事件,主线程可以定期测试该事件,并在需要时等待。
(请注意,这里有两种类型的事件,按键事件和 的设置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')
添加回答
举报