Python在单击时获取鼠标x,y位置 [英] Python get mouse x, y position on click

查看:795
本文介绍了Python在单击时获取鼠标x,y位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

使用 PyAutoGui

强大的 GUI 自动化库可让您获取屏幕大小、控制鼠标、键盘等.

要获得位置,您只需要使用 position() 函数.下面是一个例子:

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

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

相关文档链接

使用 Pynput

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

<预><代码>>>>从 pynput.mouse 导入控制器>>>鼠标 = 控制器()>>>鼠标位置(1182, 153)>>>

其中 1182 是 X 位置,153 是第二个位置.

文档

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

Windows 特定:

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

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

解决方案

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.

这篇关于Python在单击时获取鼠标x,y位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆