简体   繁体   中英

Python get mouse x, y position on click

Coming from IDL, I find it quite hard in python to get the xy 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 xy when the mouse is clicked (similar to the cursor method in IDL)?

Using PyMouse :

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

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 .

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

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

Capture the coordinates (x,y) of the mouse, when clicking with the left button, without using Tkinter ?

It's simple:

  1. Install pynput (use pip install pynput ( without the 'i' ).
  2. 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

Here is an example for canvas with tkinter:

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

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

For turtle :

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

turtle.onscreenclick(get_mouse_click_coor)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM