0

接下来是主题,我正在用 pyautogui 做一些简单的点击器,但它缺乏控制。基本上我希望能够基于 pyautogui 启动和停止不同的脚本。我的想法是结合 pynput 的 Listener 函数,但它不能正常工作。当我按下分配的键时它开始,但我无法停止它,为什么?这是一些简单的代码:

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:也许有人可以建议我另一个具有控制功能的模块,这对点击器有好处?

4

1 回答 1

1

它无法停止,因为您在执行此操作时处于无限循环中:

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% 工作。

于 2018-08-28T11:28:57.977 回答