【发布时间】:2021-08-24 18:30:30
【问题描述】:
我的代码的目的是非常快速地连续输入一个字母。它在按下某个键时启动(在本例中为 f3),并在按下另一个键时停止(f4)。我的代码目前看起来像这样。
from pynput.keyboard import Controller, Listener
import time
keyboard = Controller()
confirm = False
def on_press(key):
if "f3" in str(key):
global confirm
confirm = True
while confirm:
keyboard.press('e')
keyboard.release('e')
time.sleep(0.10)
elif "Key." in str(key):
pass
def exit_loop(key):
if "f4" in str(key):
global confirm
confirm = False
elif "Key." in str(key):
pass
with Listener(on_press=on_press) as ListenerStart:
ListenerStart.join()
with Listener(on_press=exit_loop) as ListenerEnd:
ListenerEnd.join()
我的问题是,当使用 f3 键启动程序时,我无法使用 f4 停止程序。此外,该程序应该暂停,而不是退出。任何帮助,将不胜感激。谢谢。
【问题讨论】:
-
你运行
while-loop 会阻塞所有代码 - 你应该在单独的线程中运行它。 -
你应该使用一个带有
on_press的监听器来检查按下了什么键并设置一些变量,如started = True、paused = False等,它应该使用这些变量来运行或跳过里面的代码while-loop 应该在单独的线程中运行。