问题描述
问题:但我得到的是一个无限循环,因为它不能在循环为真时听另一个键!
from pynput import keyboard
def on_press(key):
if key == keyboard.Key.f9:
while True:
print("loading")
if key == keyboard.Key.f10:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
编辑
我确实解释错了一部分,我想在某个键 WAS 按下时进行循环。
解决方法
您不能在 while True
内运行 on_press
(或任何长时间运行的函数)
因为它阻塞了 Listener
。您必须在单独的 thread
中运行它。
您需要 on_press
来创建和启动 thread
。
然后on_release
停止thread
。
它需要全局变量。 IE。 running
为此。
我仅使用 datetime
来查看它是否显示新行。
from pynput import keyboard
import threading
import datetime
# --- functions ---
def loading():
while running:
print("loading",datetime.datetime.now()) #,end='\r')
def on_press(key):
global running # inform function to assign (`=`) to external/global `running` instead of creating local `running`
if key == keyboard.Key.f9:
running = True
# create thread with function `loading`
t = threading.Thread(target=loading)
# start thread
t.start()
if key == keyboard.Key.f10:
# stop listener
return False
def on_release(key):
global running # inform function to assign (`=`) to external/global `running` instead of creating local `running`
if key == keyboard.Key.f9:
# to stop loop in thread
running = False
#--- main ---
with keyboard.Listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
,
按键被按下时的解决方案。 Admin
Admin