您可以使用mouse https://pypi.org/project/mouse/模块 (pip install mouse
)设置鼠标挂钩(热键),让您触发全局点击。但是,为了管理此单击的开始和结束,您将需要使用一个新线程(here https://realpython.com/intro-to-python-threading/如果您想了解更多信息,这是对线程的简短介绍)。当您按下热键时,您将想要启动一个线程。该线程将继续单击,直到您触发停止它的事件。您将通过释放热键来触发此事件。因此,当您按下热键时,线程(以及随之而来的点击)将开始,当您松开热键时,线程将结束。
下面是一段使用鼠标中键(滚动)作为热键来完成此操作的代码:
import mouse # pip install mouse
import threading
import pyautogui
pyautogui.PAUSE = 0.1 # set the automatic delay between clicks, default is 0.1
def repeat_function(kill_event):
# as long as we don't receive singal to end, keep clicking
while not kill_event.is_set():
pyautogui.click()
while True:
# create the event that will kill our thread, don't trigget it yet
kill_event = threading.Event()
# create the thread that will execute our clicking function, don't start it yet
new_thread = threading.Thread(target=lambda: repeat_function(kill_event))
# set a hook that will start the thread when we press middle mouse button
mouse.on_button(new_thread.start, (), mouse.MIDDLE, mouse.DOWN)
# set a hook that will kill the thread when we release middle button
mouse.on_button(kill_event.set, (), mouse.MIDDLE, mouse.UP)
# wait for user to use the hotkey
mouse.wait(mouse.MIDDLE, mouse.UP)
# remove hooks that used the killed thread and start again with a new one
mouse.unhook_all()
如果您想使用鼠标右键,请替换mouse.MIDDLE
with mouse.RIGHT
。我不建议使用鼠标左键作为热键,因为 pyautogui 会模拟单击此按钮并可能破坏程序。如果您想使用键盘上的某个键作为热键,请查看keyboard https://pypi.org/project/keyboard/模块。那里的概念完全相同。
请注意,在实现此代码时,在等待热键并对其进行处理时,它将无法执行任何其他操作。如果您想按原样使用它,则需要将其用作单独的 python 程序。您还可以实现此代码以在另一个程序期间在单独的线程中运行,但将其作为独立脚本启动肯定会更容易。