Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if the left mouse click is pressed

I am using PyAutoGUI library. How can I know if the left mouse button is pressed?

This is what I want to do:

if(leftmousebuttonpressed):
   print("left")
else:
   print("nothing")
like image 675
Coding4Life Avatar asked Aug 30 '16 19:08

Coding4Life


2 Answers

(I'm the author of PyAutoGUI.) I can confirm that currently PyAutoGUI can't read/record clicks or keystrokes. These features are on the roadmap, but there aren't any resources or timelines dedicated to them currently.

like image 57
Al Sweigart Avatar answered Sep 22 '22 00:09

Al Sweigart


How to know if left mouse click is pressed?

A simple version of the code inspired from the original documentation:

from pynput import mouse

def on_click(x, y, button, pressed):
    if button == mouse.Button.left:
        print('{} at {}'.format('Pressed Left Click' if pressed else 'Released Left Click', (x, y)))
        return False # Returning False if you need to stop the program when Left clicked.
    else:
        print('{} at {}'.format('Pressed Right Click' if pressed else 'Released Right Click', (x, y)))

listener = mouse.Listener(on_click=on_click)
listener.start()
listener.join()

Like Sir Al Sweigart mentioned in the comment above, I looked for pynput module which works perfect. See documentation and PyPi instructions at:

  • https://pynput.readthedocs.io/
  • https://pypi.org/project/pynput/

Install the library using pip: pip install pynput

Monitoring other events (e.g. Mouse move, click, scroll)

See the code under Monitoring the mouse heading from original documentation. https://pynput.readthedocs.io/en/latest/mouse.html#monitoring-the-mouse

like image 42
Ali Sajjad Avatar answered Sep 21 '22 00:09

Ali Sajjad