Detect mouse clicks in Python with position using pynput

In this tutorial, you will learn how to detect mouse clicks in Python. This program will exactly print the location and the button name which is clicked. We have to install pynput package for this task.

Here we will be only using pynput.mouse to print mouse click events.

Firstly, we need to install pynput package in our Python environment.

Go to cmd and type pip to ensure if it is set up or not. If it is already set up then the cmd console will not generate any errors. After that type pip install pynput in cmd for installing pynput package.

After successfully installing pynput follow the steps of writing code given below.

Detect mouse clicks in Python – Code

Import pynput Python library with the sub-package mouse along with Listener.

from pynput.mouse import Listenerdef click(x,y,button,pressed):
    print("Mouse is Clicked at (",x,",",y,")","with",button)

Now define a function named click which will take four arguments. (x,y) is the location of the mouse pointer and the button is the name of the button. This function will print the location and button name which is being pressed.

def click(x,y,button,pressed):
    print("Mouse is Clicked at (",x,",",y,")","with",button)

In the below chunk of code, we use with statement for mouse clicking events which creates the object listener.

with Listener(on_click=click) as listener:
    listener.join()

Now we will see full code.

from pynput.mouse import Listener
def click(x,y,button,pressed):
    print("Mouse is Clicked at (",x,",",y,")","with",button)


with Listener(on_click=click) as listener:
    listener.join()

It will produce the output as shown below. We have successfully detected our mouse clicks.

Output:

Mouse is Clicked at ( 729 , 403 ) with Button.left
Mouse is Clicked at ( 729 , 403 ) with Button.right
Mouse is Clicked at ( 729 , 403 ) with Button.right

We have successfully detected mouse clicks.

Leave a Reply

Your email address will not be published. Required fields are marked *