在Python中获取光标位置

rec*_*gle 27 python windows

是否可以使用标准Python库在Windows中获得整体光标位置?

Mic*_*ied 34

使用标准ctypes库,这应该产生当前的屏幕鼠标坐标,而不需要任何第三方模块:

from ctypes import windll, Structure, c_long, byref


class POINT(Structure):
    _fields_ = [("x", c_long), ("y", c_long)]



def queryMousePosition():
    pt = POINT()
    windll.user32.GetCursorPos(byref(pt))
    return { "x": pt.x, "y": pt.y}


pos = queryMousePosition()
print(pos)
Run Code Online (Sandbox Code Playgroud)

我应该提一下,这段代码来自于此处的一个示例. 因此,我认为这个解决方案可以归功于Nullege.com.

  • 我对此进行了修复,因为它会导致人们可能不会立即注意到的错误:光标位置是有符号的,而不是无符号的,如果鼠标位于主显示器左侧的监视器上,则可能为负值。使用“c_ulong”,您最终会得到像 4294967196 这样的坐标,而不是 -100。(它也可以垂直发生,但不太常见。) (4认同)
  • Bahaha,当我研究这个时,刚刚在Nullege发现了相同的片段.但这应该是公认的答案,因为它不使用第三方代码,它就像一个魅力. (2认同)

pyf*_*unc 23

win32gui.GetCursorPos(point)
Run Code Online (Sandbox Code Playgroud)

这将在屏幕坐标中检索光标的位置 - point =(x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()
Run Code Online (Sandbox Code Playgroud)

检索有关全局游标的信息.

链接:

我假设您将使用python win32 API绑定或pywin32.


Mic*_*las 12

您不会在标准Python库中找到此类函数,而此函数是Windows特定的.但是,如果您使用ActiveState Python,或者只是将win32api模块安装到标准Python Windows安装,您可以使用:

x, y = win32api.GetCursorPos()
Run Code Online (Sandbox Code Playgroud)

  • 通过 pip install pypiwin32 安装它 (3认同)

小智 7

这是可能的,而且还没有那么混乱!只需使用:

from ctypes import windll, wintypes, byref

def get_cursor_pos():
    cursor = wintypes.POINT()
    windll.user32.GetCursorPos(byref(cursor))
    return (cursor.x, cursor.y)
Run Code Online (Sandbox Code Playgroud)

使用的答案pyautogui让我想知道该模块是如何做到这一点的,所以我看了看,这就是如何做的。


Pun*_*rud 6

对于使用本机库的 Mac:

import Quartz as q
q.NSEvent.mouseLocation()

#x and y individually
q.NSEvent.mouseLocation().x
q.NSEvent.mouseLocation().y
Run Code Online (Sandbox Code Playgroud)

如果未安装Quartz包装器:

python3 -m pip install -U pyobjc-framework-Quartz
Run Code Online (Sandbox Code Playgroud)

(问题指定的是Windows,但很多Mac用户都是因为标题才来到这里的)


rec*_*gle 5

我发现了一种不依赖于非标准库的方法!

在Tkinter找到了这个

self.winfo_pointerxy()
Run Code Online (Sandbox Code Playgroud)

  • 实际上,应该首先创建一个实例。就像`p = Tkinter.Tk()`,最后得到`p.winfo_pointerxy()`,它返回当前光标位置的元组:) (2认同)

Abh*_*nav 5

Using pyautogui

To install

pip install pyautogui

and to find the location of the mouse pointer

import pyautogui
print(pyautogui.position())
Run Code Online (Sandbox Code Playgroud)

This will give the pixel location to which mouse pointer is at.