Home > database >  Making an autoclicker in python?
Making an autoclicker in python?

Time:01-08

I have designed this simple autoclicker in python using the pynput library

import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode

TOGGLE_KEY = KeyCode(char="t")
activated = False
mouse = Controller()

def on_press(key):
    global activated
    if key == TOGGLE_KEY:
        activated = not activated

        while activated:
            mouse.click(Button.left, 1)
            time.sleep(0.01)


listner = Listener(on_press=on_press)
listner.start()

input()

This code activates a listner and when the user presses any key it calls the on_press function which checks if the button is equal to 't' then it inverts the property of activated and starts the while loop

I tried the above code and it worked but when I pressed 't' again the autoclicker did not switch off

CodePudding user response:

I believe you are stuck in your while activated: loop. Pushing T again does not make the function run again unless the first function has stopped. A simple solution would be to put the click event in its own thread.

import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode

TOGGLE_KEY = KeyCode(char="t")
activated = False
mouse = Controller()

def on_press(key):
    global activated
    if key == TOGGLE_KEY:
        activated = not activated

def doClick():
    global activated
    while True:
        if activated:
            mouse.click(Button.left, 1)
            time.sleep(0.01)

threading.Thread(target = doClick).start()

listner = Listener(on_press=on_press)
listner.start()

input()

CodePudding user response:

I think the problem is that the program is stucked in the loop. A solution I found is to use a thread

import threading
import time

from pynput.keyboard import Listener, KeyCode
from pynput.mouse import Controller

mouse = Controller()

class Clicker(threading.Thread):
    __TOGGLE_KEY = KeyCode(char="t")
    __activated = False

    def run(self) -> None:
        super().run()
        while True:
            if self.__activated:
                # mouse.click(Button.left, 1)
                time.sleep(1)
                print("activated")

    def keyboard_listener(self, key) -> None:
        if key == self.__TOGGLE_KEY:
            self.__activated = not self.__activated


clicker = Clicker()
listner = Listener(on_press=clicker.keyboard_listener)
listner.start()
clicker.start()
print("Listener started")

input()
  • Related