How to make a Python auto clicker?

Last Updated : 19 Jan, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will see how to create an auto-clicker using Python. The code will take input from the keyboard when the user clicks on the start key and terminates auto clicker when the user clicks on exit key, the auto clicker starts clicking wherever the pointer is placed on the screen. We are going to use the pynput module here. 

What is Auto Clicker?

Auto-Clicker is a script where you can auto control mouse and keyboard as many numbers of times as you want. It is controlled using user-defined keys. It works on various platforms like Windows, Mac and Linux. Auto clicker is present in pywin32 module.

Approach:

In this project, we will use a cross-platform module pynput to control the mouse and monitor the keyboard at the same time to create simple auto-clicker. To check for mouse events we will install pynput module (used to control the mouse) for this execute, pip install pynput in cmd. 

Note: If you’re stuck on how to set up python-pip package on your system then click here

Installation of pynput module

Verify whether the pynput module has been successfully installed into your working environment for this, open IDLE on the system that is cmd or Python Shell. Execute the command import pynput, after executing this the output should give zero errors which means your module is successfully installed. 

Verifying module installation

Implementation:

Let’s now proceed with the code that is required to build an Auto-clicker using Python. Follow the below steps to create an auto-clicker:

Step 1: Import time and threading then import Button and Controller from pynput.mouse module. Import Listener and KeyCode from pynput.keyboard.

Python3




# importing time and threading
import time
import threading
from pynput.mouse import Button, Controller
  
# pynput.keyboard is used to watch events of
# keyboard for start and stop of auto-clicker
from pynput.keyboard import Listener, KeyCode


Step 2: Create four variables  as mentioned below,

  • delay: Delay between each click (in seconds)
  • button: Button is used to click in whatever direction you want to.  Button.left | Button.middle | Button.right
  • start_stop_key: The key used for start and stop of the click while you run the program for executing the auto clicker. It should be from a key class or set using KeyCode.
  • exit_key: The key used to terminate the auto clicker that is being executed. This should be from the key class or set using KeyCode.

Python3




# four variables are created to
# control the auto-clicker
delay = 0.001
button = Button.right
start_stop_key = KeyCode(char='a')
stop_key = KeyCode(char='b')


Step 3: Create a class extending threading.Thread. Pass delay and button to the class that have two flags to check if the program is executed or not.

Python3




# threading.Thread is used 
# to control clicks
class ClickMouse(threading.Thread):
    
  # delay and button is passed in class 
  # to check execution of auto-clicker
    def __init__(self, delay, button):
        super(ClickMouse, self).__init__()
        self.delay = delay
        self.button = button
        self.running = False
        self.program_running = True


Step 4: Add methods to control the threads externally.

Python3




def start_clicking(self):
        self.running = True
  
def stop_clicking(self):
        self.running = False
  
def exit(self):
        self.stop_clicking()
        self.program_running = False


 

Step 5: A method is created when the thread starts, the program_running runs on loop until the value comes out to be true and also create another loop inside the existing loop where it checks if running is set to true or not. In case, we are inside both loops, it will click on the set button and sleep for the set delay.

Python3




# method to check and run loop until 
# it is true another loop will check 
# if it is set to true or not, 
# for mouse click it set to button 
# and delay.
def run(self):
    while self.program_running:
        while self.running:
            mouse.click(self.button)
            time.sleep(self.delay)
        time.sleep(0.1)


Step 6: Creating an instance for the mouse controller, then create ClickMouse thread. Start the instance to move into the loop inside the run method.

Python3




# instance of mouse controller is created
mouse = Controller()
click_thread = ClickMouse(delay, button)
click_thread.start()


 

Step 7: Create a method on_press which takes a key as an argument and sets up a keyboard listener. The start_stop_key matches with a start key (a) when it is executed. Then the click is to be terminated when running flag is set to True in the thread. Exit method is called in the method if the exit key (b) is executed and stop the listener.

Python3




# on_press method takes
# key as argument
  
  
def on_press(key):
  
  # start_stop_key will stop clicking
  # if running flag is set to true
    if key == start_stop_key:
        if click_thread.running:
            click_thread.stop_clicking()
        else:
            click_thread.start_clicking()
  
    # here exit method is called and when
    # key is pressed it terminates auto clicker
    elif key == stop_key:
        click_thread.exit()
        listener.stop()
  
  
with Listener(on_press=on_press) as listener:
    listener.join()


After the code is run we can see in the output as shown below, it shows the number of clicks the auto-clicker has made after the code is implemented. It is compatible with Windows, Mac and Linux. Auto-Clicker is helpful software for the systems as it let’s save a reasonable amount of time that is spent on repeated amount of clicks. 

Below is the complete program:

Python3




# importing time and threading
import time
import threading
from pynput.mouse import Button, Controller
  
# pynput.keyboard is used to watch events of 
# keyboard for start and stop of auto-clicker
from pynput.keyboard import Listener, KeyCode
  
  
# four variables are created to 
# control the auto-clicker
delay = 0.001
button = Button.right
start_stop_key = KeyCode(char='a')
stop_key = KeyCode(char='b')
  
# threading.Thread is used 
# to control clicks
class ClickMouse(threading.Thread):
    
  # delay and button is passed in class 
  # to check execution of auto-clicker
    def __init__(self, delay, button):
        super(ClickMouse, self).__init__()
        self.delay = delay
        self.button = button
        self.running = False
        self.program_running = True
  
    def start_clicking(self):
        self.running = True
  
    def stop_clicking(self):
        self.running = False
  
    def exit(self):
        self.stop_clicking()
        self.program_running = False
  
    # method to check and run loop until 
    # it is true another loop will check 
    # if it is set to true or not, 
    # for mouse click it set to button 
    # and delay.
    def run(self):
        while self.program_running:
            while self.running:
                mouse.click(self.button)
                time.sleep(self.delay)
            time.sleep(0.1)
  
  
# instance of mouse controller is created
mouse = Controller()
click_thread = ClickMouse(delay, button)
click_thread.start()
  
  
# on_press method takes 
# key as argument
def on_press(key):
    
  # start_stop_key will stop clicking 
  # if running flag is set to true
    if key == start_stop_key:
        if click_thread.running:
            click_thread.stop_clicking()
        else:
            click_thread.start_clicking()
              
    # here exit method is called and when 
    # key is pressed it terminates auto clicker
    elif key == stop_key:
        click_thread.exit()
        listener.stop()
  
  
with Listener(on_press=on_press) as listener:
    listener.join()


Now let’s execute the python program we’ve written and then press the start (a) and stop (a) keys in order to initiate the auto clicker. 

Output:



Previous Article
Next Article

Similar Reads

How to Define an Auto Increment Primary Key in PostgreSQL using Python?
Prerequisite: PostgreSQL Python has various database drivers for PostgreSQL. Currently, most used version is psycopg2 because it fully implements the Python DB-API 2.0 specification. The psycopg2 provides many useful features such as client-side and server-side cursors, asynchronous notification and communication, COPY command support, etc. Install
3 min read
Auto Search StackOverflow for Errors in Code using Python
Ever faced great difficulty in copying the error you're stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer? Worry Not, Here's the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on Stack Overflow, and opens up the few tabs related t
3 min read
How to Build a Simple Auto-Login Bot with Python
In this article, we are going to see how to built a simple auto-login bot using python. In this present scenario, every website uses authentication and we have to log in by entering proper credentials. But sometimes it becomes very hectic to login again and again to a particular website. So, to come out of this problem lets, built our own auto logi
3 min read
enum.auto() in Python
With the help of enum.auto() method, we can get the assigned integer value automatically by just using enum.auto() method. Syntax : enum.auto()Automatically assign the integer value to the values of enum class attributes.Example #1 : In this example we can see that by using enum.auto() method, we are able to assign the numerical values automaticall
1 min read
PyQt5 – How to auto resize Label | adjustSize QLabel
During the designing of the GUI (Graphical User Interface) application there is a need to display plain text as information where label is used, but sometimes information text could be large or much smaller and it is difficult to use resize() method so have to auto adjust the size of the label according to the text, in order to do so adjustSize() m
2 min read
PyQt5 - Auto Adjusting Progress Bar size
In this article we will see how to adjust the size of progress bar. Adjusting size means setting the size of progress bar as much as it is needed, nor too big nor too small, just the size which can comprise all the text in it. In order to do this we will use adjustSize method. Note : Adjusting size will set the minimum required size. It doesn't dep
2 min read
PyQt5 QSpinBox - Checking if Auto Fill Background property is enabled or not
In this article we will see how we can see if the auto fill property of the spin box is enabled or not, this property will cause Qt to fill the background of the spin box before invoking the paint event. The color used is defined by the QPalette.Window color role from the spin box's palette. By default this property is false although we can change
2 min read
PyQt5 QSpinBox - Setting Auto Fill Background property
In this article we will see how we can set the auto fill property of the spin box, this property will cause Qt to fill the background of the spin box before invoking the paint event. The color used is defined by the QPalette.Window color role from the spin box's palette. By default this property is false. This property should be handled with cautio
2 min read
PyQt5 QCalendarWidget - Getting Auto Fill Background Property
In this article we will see how we get the auto fill property of the QCalendarWidget, this property will cause Qt to fill the background of the calendar before invoking the paint event. The color used is defined by the QPalette. By default this property is false which can be changed with the help of setAutoFillBackground method. In order to do this
2 min read
PyQt5 QCalendarWidget - Enabling/Disabling Auto Fill Background Property
In this article we will see how we enable or disable the auto fill property of the QCalendarWidget, this property will cause Qt to fill the background of the calendar before invoking the paint event. The color used is defined by the QPalette. By default this property is false.This property should be handled with caution in conjunction with Qt Style
2 min read
PyQt5 QCommandLinkButton - Setting Auto Default Property
In this article we will see how we can set the auto default property of the QCommandLinkButton. If this property is set to true then the command link button is an auto default button. In some GUI styles a default button is drawn with an extra frame around it, up to 3 pixels or more. Qt automatically keeps this space free around auto-default buttons
2 min read
PyQt5 QCommandLinkButton - Getting Auto Default Property
In this article we will see how we can get the auto default property of the QCommandLinkButton. If this property is set to true then the command link button is an auto default button. In some GUI styles a default button is drawn with an extra frame around it, up to 3 pixels or more. Qt automatically keeps this space free around auto-default buttons
2 min read
PyQt5 QCommandLinkButton - Getting Auto Repeat Interval Time
In this article, we will see how we can get the auto repeat interval time of the QCommandLinkButton.It defines the length of the auto-repetition interval in milliseconds when auto repeat property is enabled. In auto repeat property the pressed, released and clicked signals are emitted at regular intervals when the command link button is down. Auto
2 min read
PyQt5 QCommandLinkButton - Setting Auto Repeat Delay Time
In this article we will see how we can set the auto repeat delay time of the QCommandLinkButton.It defines the initial delay in milliseconds before auto-repetition kicks in. In auto repeat property the pressed, released, and clicked signals are emitted at regular intervals when the command link button is down. Auto repeat property is off by default
2 min read
PyQt5 QCommandLinkButton - Getting Auto Repeat Delay Time
In this article we will see how we can get the auto-repeat delay time of the QCommandLinkButton.It defines the initial delay in milliseconds before auto-repetition kicks in. In auto repeat property the pressed, released, and clicked signals are emitted at regular intervals when the command link button is down. Auto repeat property is off by default
2 min read
PyQt5 QCommandLinkButton - Setting Auto Exclusive Property
In this article we will see how we can set the auto exclusive property of the QCommandLinkButton. If auto-exclusivity is enabled, checkable command link buttons that belong to the same parent widget behave as if they were part of the same exclusive button group. In an exclusive command link button group, only one button can be checked at any time;
2 min read
PyQt5 QCommandLinkButton - Getting Auto Exclusive Property
In this article we will see how we can get the auto exclusive property of the QCommandLinkButton. If auto-exclusivity is enabled, checkable command link buttons that belong to the same parent widget behave as if they were part of the same exclusive button group. In an exclusive command link button group, only one button can be checked at any time;
2 min read
PyQt5 QCommandLinkButton - Setting Auto Repeat Property
In this article we will see how we can set the auto repeat property of the QCommandLinkButton. If auto repeat property is enabled, then the pressed, released, and clicked signals are emitted at regular intervals when the command link button is down. Auto repeat property is off by default. The initial delay and the repetition interval are defined in
2 min read
PyQt5 QCommandLinkButton - Getting Auto Repeat Property
In this article we will see how we can get the auto repeat property of the QCommandLinkButton. If auto repeat property is enabled, then the pressed, released, and clicked signals are emitted at regular intervals when the command link button is down. Auto repeat property is off by default. The initial delay and the repetition interval are defined in
2 min read
PyQt5 QCommandLinkButton - Setting Auto Repeat Interval Time
In this article, we will see how we can set the auto-repeat interval time of the QCommandLinkButton.It defines the length of the auto-repetition interval in milliseconds when auto repeat property is enabled. In auto-repeat property, the pressed, released and clicked signals are emitted at regular intervals when the command link button is down. Auto
2 min read
MoviePy – Turning on auto play for video clip file
In this article we will see how we can turn on the auto play of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We can display a video with the help of ipyt
2 min read
PyQt5 QListWidget – Setting Auto Scroll property
In this article we will see how we can set auto scroll property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether autoscrolling in drag move even
2 min read
PyQt5 QListWidget – Getting Auto Scroll Property
In this article we will see how we can get auto scroll property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether autoscrolling in drag move even
2 min read
PyQt5 QListWidget – Setting Auto Scroll Margin
In this article we will see how we can set auto scroll margin of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds the size of the area when auto scrolling
2 min read
PyQt5 QListWidget – Getting Auto Scroll Margin
In this article we will see how we can get auto scroll margin of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds the size of the area when auto scrolling
2 min read
PyQtGraph – Auto Adjust the size of Image View
In this article, we will see how we can auto adjust the size of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). W
4 min read
PyQtGraph – Auto Range of Image View
In this article, we will see how we can set an automatic range of image view in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget use
3 min read
PyQtGraph – Auto Levels of Image View
In this article, we will see how we can set automatic levels of image view in PyQTGraph. The PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget u
3 min read
Introduction to auto-py-to-exe Module
In the world of Python development, sharing your application with users who may not have Python installed can be challenging. auto-py-to-exe is a powerful tool that simplifies this process by converting Python scripts into standalone executable files (.exe) for Windows. This makes it easier to distribute your Python applications without requiring u
5 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Practice Tags :
three90RightbarBannerImg