Reputation: 69
The subject is next, I´m doing some siple clickers with pyautogui but it lacks of control. Basically I want to be able to start and stop different scripts based on pyautogui. My idea was to combine the Listener function from pynput, but it doesn´t work properly . It starts when I press the assigned key, but I cannot stop it, why? Here is some simle code:
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()
I also have tried this loop:
while True:
if key==Key.enter:
pg.moveRel(x, 0, duration=0.2)
else:
return(False)
time.sleep(1)
but nothing works.
UPD: Maybe someone can suggest me another module with controlling features, which can be good for clicker?
Upvotes: 0
Views: 4980
Reputation: 384
It's failing to stop because you are in a infinite loop when you do this:
while key is not Key.enter:
due to the fact that your on_press can't be called again and therefore the variable key will never change.
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()
To use this, you press space to start your mouse movement, then you can stop it by pressing enter. After this, you need to press esc key to reset the event that stops it which means to do this macro twice in a row you need to press:
space (start the macro)
enter (stop/kill the macro)
esc (reset flag, if you press space after this you can start the macro again)
I've tested it and it works 100%.
Upvotes: 2