-1

I want to create a python script that stores the mouse click's co-ordiantes. The co-ordinates should save in a file. I came across the following thread but I couldn't get it working. The script should capture mouse cordinates all over the desktop and not to a particular window/application.

Python get mouse x, y position on click

Thank you

  • 1
    I'm afraid "I couldn't get it working" is too broad to be answerable. Please show the code you tried and explain what didn't work at minimum. Thank you. – ggorlen Jan 07 '20 at 05:57
  • https://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python should help. – Arundeep Chohan Jan 07 '20 at 06:06
  • @ggorlen I tried to use pyautogui and pymouse. It shows the x,y co-ordinates of the mouse when i click on run and nothing else. As mentioned i want to create python code that shows the x,y coordinates of mouse whenever it is clicked on any application or at desktop. I am sorry if my question could not be understood. >>> import pymouse >>> mouse = pymouse.PyMouse() >>> mouse.position() – Aniket Paul Jan 07 '20 at 06:19

1 Answers1

0

Try this solution:

from pynput import mouse

def on_click(x, y, button, pressed):
     print(x,y)

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

The result of above code is:

830 345 Button.left True
830 345 Button.left False

The values of above code will print twice i.e one for co-ordinate value for button pressed and one co-ordinate value for button released.

So to get both the co-ordinates of mouse click event and released event use the above code.

So to print the value of co-ordinates where mouse button is clicked use the below code:

from pynput import mouse

def on_click(x, y, button, pressed):
    if pressed == True:
        print(x,y)

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

AND

So to print the value of co-ordinates where mouse button is released use the below code:

from pynput import mouse

def on_click(x, y, button, pressed):
    if pressed == False:
        print(x,y)

with mouse.Listener(on_click=on_click) as listener:
     listener.join()
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20