Python在单击时获取鼠标x,y位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25848951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:44:18  来源:igfitidea点击:

Python get mouse x, y position on click

pythonpython-2.7

提问by ben_bo

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

来自 IDL,我发现在 python 中使用一种不像 tkinter 那样矫枉过正的方法在一次左键单击中获得鼠标的 xy 位置非常困难。有谁知道一个python包,它包含一个方法,当点击鼠标时简单地返回xy(类似于IDL中的光标方法)?

回答by falsetru

Using PyMouse:

使用PyMouse

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

回答by Simon

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

您可以使用许多库。这里有两个第三方:

Using PyAutoGui

使用 PyAutoGui

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

强大的 GUI 自动化库允许您获取屏幕大小、控制鼠标、键盘等。

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

要获得位置,您只需要使用该position()功能。下面是一个例子:

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

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

其中1358是 X 位置,146是 Y 位置。

Relavent link to the documentation

文档的相关链接

Using Pynput

使用 Pynput

Another (more minimalistic) library is Pynput:

另一个(更简约的)库是 Pynput:

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

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

哪里1182是 X 位置,153是第二个。

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.

这个库很容易学习,不需要依赖项,这使得这个库非常适合这样的小任务(PyAutoGui 会有点矫枉过正)。再一次,它没有提供这么多功能。

Windows Specific:

Windows 特定:

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

对于依赖于平台但默认库选项(尽管您可能仍然认为它们是矫枉过正的)可以在这里找到:在 Python 中获取光标位置

回答by Stanley

Here is an example for canvas with tkinter:

这是带有 tkinter 的画布示例:

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

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

回答by Michael Wang

Use pygame

使用 pygame

import pygame

mouse_pos = pygame.mouse.get_pos()

This returns the x and y position of the mouse.

这将返回鼠标的 x 和 y 位置。

See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos

请参阅此网站:https: //www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos