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)?
-
6I've voted to re-open this question. It was closed as "too broad" which I disagree with. The OP is asking for a method to obtain coordinates on mouse click without having to resort to `tkinter` overkill (e.g.: http://stackoverflow.com/questions/5501192/how-to-display-picture-and-get-mouse-click-coordinate-on-it) What's too broad about this? – Gabriel Mar 29 '17 at 13:44
9 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.
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.

- 11,201
- 10
- 62
- 89
-
-
PyAutoGui uses PyScreeze to continuously capture the screen, I assume since the CPU usage is extremely high for something as simple as mouse tracking. Now *that's* what *I* consider overkill. – zamarov Oct 18 '22 at 15:13
Using PyMouse
:
>>> import pymouse
>>> mouse = pymouse.PyMouse()
>>> mouse.position()
(231L, 479L)

- 357,413
- 63
- 732
- 636
-
2See also the library [PyUserInput](https://github.com/SavinaRoja/PyUserInput), which integrates PyMouse's code and appears to be more current. One of its dependencies, PyHook, is officially 32 bit only, but a third-party 64 bit installer can be found [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook). – Kevin Sep 15 '14 at 13:44
-
You can listen for mouse click events by subclassing the `PyMouseEvent` class. See the "Clickonacci" example on the PyUserInput page. – Kevin Sep 15 '14 at 13:44
-
1This doesn't answer how to get the position *when the mouse is clicked*. – mkrieger1 Mar 07 '22 at 22:34
As an example, for plot or images, it is possible to use the matplotlib
tool called ginput
.
At every click of the mouse the [x,y]
coordinates of the selected point are stored in a variable.
# show image
fig, ax=plt.subplots()
ax.imshow(img)
# select point
yroi = plt.ginput(0,0)
using ginput(0,0)
you can select any points on the plot or image.
here the link for the ginput documentation
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.ginput.html

- 667
- 1
- 7
- 27

- 143
- 3
- 14
I made this the other day. It a function to get color or pos on right click / left click:
#Add Any helpfull stuff in functions here for later use
def GetMouseInfos(WhatToGet="leaving emety will get you x and y", GetXOnly=False, GetYOnly=False, GetColor=False, Key='Right', OverrideKey=False):#gets color of whats under Key cursor on right click
try:
import win32api
except ModuleNotFoundError:
print("win32api not found, to install do pip install pywin32")
try:
import time
except ModuleNotFoundError:
print("time not found, to install do pip install time?")
try:
import pyautogui
except ModuleNotFoundError:
print("py auto gui not found, to install do pip install pyautogui")
#--------------------------------------------------------------
#above checks if needed modules are installed if not tells user
#code below is to get all varibles needed
#---------------------------------------------------------------
print(WhatToGet)
if OverrideKey:
Key_To_click = Key
if Key == 'Left':
Key_To_click = 0x01
if Key == 'Right':
Key_To_click = 0x02
if Key == 'Wheel':
Key_To_click = 0x04
state_left = win32api.GetKeyState(Key_To_click) # Left button up = 0 or 1. Button down = -127 or -128
IsTrue = True
while IsTrue:
a = win32api.GetKeyState(Key_To_click)
if a != state_left: # Button state changed
state_left = a
if a < 0:
global Xpos, Ypos
Xpos, Ypos = win32api.GetCursorPos()
x, y = pyautogui.position()
pixelColor = pyautogui.screenshot().getpixel((x, y))
else:
posnowX, posnowY = win32api.GetCursorPos()
win32api.SetCursorPos((posnowX, posnowY))
IsTrue = False#remove this for it to keep giving coords on click without it just quitting after 1 click
time.sleep(0.001)
#--------------------------------------------------------------------
#The Code above is the code to get all varibles and code below is for the user to get what he wants
#--------------------------------------------------------------------
if GetXOnly: #Checks if we should get Only X (def options) the command to do this would be GetKeyInfos("Click To get X ONLY", True)
if GetYOnly:
return(Xpos , Ypos)
if GetColor:
return(Xpos, pixelColor)
return(Xpos)
if GetYOnly: #Checks if we should get Only Y (def options) the command to do this would be GetKeyInfos("Click To get X ONLY",False, True)
if GetXOnly:
return(Xpos , Ypos)
if GetColor:
return(Ypos, pixelColor)
return(Ypos)
if GetColor:
return(pixelColor) #Checks
return(Xpos, Ypos)
# getKeyinfos("Anything here without any other guidelines will give u x and y only on right click")

- 36,675
- 19
- 86
- 83

- 31
- 1
Use pygame
import pygame
mouse_pos = pygame.mouse.get_pos()
This returns the x and y position of the mouse.
See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos

- 145
- 11
-
if I use this I get `pygame.error: video system not initialized`, and if I use `pygame.init()` then I get a constant (0,0) position wherever my cursor is. – Hadi Farah Jan 10 '21 at 18:27
-
1This doesn't answer how to get the position *when the mouse is clicked*. – mkrieger1 Mar 07 '22 at 22:35
-
That returns the x & y position of the mouse in a pygame window, not in the entire screen. – hotwheel2007 May 31 '22 at 23:47
For turtle :
def get_mouse_click_coor(x, y):
print(x, y)
turtle.onscreenclick(get_mouse_click_coor)

- 11
- 1
-
add `turtle.mainloop()` in the end so the screen remains open when you click. – quicksilver Dec 31 '21 at 04:13
Capture the coordinates (x,y) of the mouse, when clicking with the left button, without using Tkinter
?
It's simple:
- Install
pynput
(usepip install pynput
(without the 'i'). - Copy and paste this code into your editor:
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
x = x
y = y
print('X =', x, '\nY =', y)
with Listener(on_click=on_click) as listener:
listener.join()
I hope this help you =D

- 11
- 3
-
That's short. Although, what is `x=x` and `y=y`? Do you need this? How would I stop the loop, if e.g. I acquired two set of coordinates and want to continue with the program using these values? – theozh Feb 01 '23 at 12:01
You all are making it too hard, its just as easy as:
import pyautogui as pg
pos = pg.position()
# for x pos
print(pos[0])
# for y pos
print(pos[1])

- 12,788
- 2
- 23
- 50

- 193
- 6
-
This didn't answer the question. He specifically asked to return the co-ordinates, when the mouse button is clicked, without using tkinter. – C0ppert0p Jul 10 '22 at 01:38