接下来的主题是,我正在做一些pyautogui的siple答题器,但它缺乏控制。基本上我希望能够基于pyautogui启动和停止不同的脚本。我的想法是结合来自pynput的Listener函数,但它无法正常工作。当我按下指定的键时它会启动,但是我无法阻止它,为什么?这是一些simle代码:
from pynput.keyboard import Key, Controller, Listener
import time
import pyautogui as pg
pg.FAILSAFE = True
kb = Controller()
time.sleep(1)
def on_press(key):
if key == Key.space:
pg.position(500, 500)
x = 20
while key is not Key.enter:
pg.moveRel(x, 0, duration=0.2)
time.sleep(1)
with Listener(on_press=on_press) as listener:
listener.join()
我也试过这个循环:
while True:
if key==Key.enter:
pg.moveRel(x, 0, duration=0.2)
else:
return(False)
time.sleep(1)
但没有任何作用。
UPD:也许有人可以建议我另一个带控制功能的模块,这对点击器有好处吗?
它没有停止,因为当你这样做时你处于无限循环中:
while key is not Key.enter:
由于您的on_press无法再次调用,因此变量键永远不会改变。
from pynput.keyboard import Key, Controller, Listener
import time
import pyautogui as pg
import threading
pg.FAILSAFE = True
kb = Controller()
time.sleep(1)
threadExitFlag = threading.Event()
threadVar = None
def mouse_move_thread(threadExitFlag):
pg.position(500, 500)
x = 20
while not threadExitFlag.is_set():
pg.moveRel(x, 0, duration=0.2)
time.sleep(1)
def on_press(key):
global threadExitFlag
if key == Key.space:
threadVar = threading.Thread(target=mouse_move_thread, args=[threadExitFlag]).start()
if key == Key.enter:
threadExitFlag.set()
#Turns this macro back on
elif key == Key.esc:
if threadExitFlag.is_set():
threadExitFlag.clear()
with Listener(on_press=on_press) as listener:
listener.join()
要使用它,按空格键开始鼠标移动,然后按Enter键即可停止它。在此之后,您需要按esc键以重置停止它的事件,这意味着您需要连续两次执行此宏:
space (start the macro)
enter (stop/kill the macro)
esc (reset flag, if you press space after this you can start the macro again)
我测试了它,它100%工作。