ben_bo
ben_bo

Reputation: 361

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)?

Upvotes: 36

Views: 163150

Answers (9)

GustavoRosasDev
GustavoRosasDev

Reputation: 51

How to Capture Mouse Click Coordinates (x, y) Without Tkinter?

First, install pynput (use pip install pynput (without the 'i')). Then, copy and paste this script into your editor:

from pynput.mouse import Listener, Button


# Function called on a mouse click
def on_click(x, y, button, pressed):
    # Check if the left button was pressed
    if pressed and button == Button.left:
        # Print the click coordinates
        print(f'x={x} and y={y}')


# Initialize the Listener to monitor mouse clicks
with Listener(on_click=on_click) as listener:
    listener.join()

It's as simple as that! This script captures the coordinates (x, y) of the mouse when clicking with the left button.

Happy coding! 🤓

Upvotes: 5

Amrit Sanjeev
Amrit Sanjeev

Reputation: 333

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])

Upvotes: -3

Anantaksh Playz
Anantaksh Playz

Reputation: 41

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")

Upvotes: 4

Deepak Sinha
Deepak Sinha

Reputation: 11

For turtle :

def get_mouse_click_coor(x, y):
    print(x, y)

turtle.onscreenclick(get_mouse_click_coor)

Upvotes: 1

vittorio
vittorio

Reputation: 143

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

Upvotes: 3

Michael Wang
Michael Wang

Reputation: 145

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

Upvotes: 2

Stanley
Stanley

Reputation: 2814

Here is an example for canvas with tkinter:

def callback(event):  
    print("clicked at: ", event.x, event.y)  

canvas.bind("<Button-1>", callback)

Upvotes: 1

Xantium
Xantium

Reputation: 11603

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.

Upvotes: 26

falsetru
falsetru

Reputation: 369394

Using PyMouse:

>>> import pymouse
>>> mouse = pymouse.PyMouse()
>>> mouse.position()
(231L, 479L)

Upvotes: 14

Related Questions