Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get mouse x, y position on click

Coming from IDL, I find it quite hard in python to get the x-y position of the mouse on a single left click using a method that is not an overkill as in tkinter. Does anyone know about a python package that contains a method simply returning x-y when the mouse is clicked (similar to the cursor method in IDL)?

like image 505
ben_bo Avatar asked Sep 15 '14 13:09

ben_bo


People also ask

How do I get the XY coordinates of a mouse Python?

To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.

How do I check my mouse position?

In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK.


1 Answers

There are a number of libraries you could use. Here are two third party ones:

Using PyAutoGui

A powerful GUI automation library allows you to get screen size, control the mouse, keyboard and more.

To get the position you just need to use the position() function. Here is an example:

>>>import pyautogui >>>pyautogui.position() (1358, 146) >>> 

Where 1358 is the X position and 146 is the Y position.

Relavent link to the documentation

Using Pynput

Another (more minimalistic) library is Pynput:

>>> from pynput.mouse import Controller >>> mouse = Controller() >>> mouse.position (1182, 153) >>> 

Where 1182 is the X position and 153 is the second.

Documentation

This library is quite easy to learn, does not require dependencies, making this library ideal for small tasks like this (where PyAutoGui would be an overkill). Once again though, it does not provide so many features though.

Windows Specific:

For platform dependant, but default library options (though you may still consider them overkills) can be found here: Getting cursor position in Python.

like image 120
Xantium Avatar answered Sep 21 '22 10:09

Xantium