鼠标位置Python Tkinter

Kyl*_*mer 17 python tkinter mouse-pointer

有没有办法获得鼠标的位置并将其设置为var?

Bry*_*ley 24

在任何时间点,您都可以使用该方法winfo_pointerxwinfo_pointery获取相对于根窗口的x,y坐标.要将其转换为绝对屏幕坐标,您可以获得winfo_pointerxwinfo_pointery,并从中减去相应的winfo_rootxwinfo_rooty

例如:

root = tk.Tk()
...
x = root.winfo_pointerx()
y = root.winfo_pointery()
abs_coord_x = root.winfo_pointerx() - root.winfo_rootx()
abs_coord_y = root.winfo_pointery() - root.winfo_rooty()
Run Code Online (Sandbox Code Playgroud)

  • 似乎相对坐标和绝对坐标混淆了 (5认同)

unu*_*tbu 23

您可以设置回调以对<Motion>事件做出反应:

import Tkinter as tk
root = tk.Tk()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

root.bind('<Motion>', motion)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

我不确定你想要什么样的变量.在上面,我设置局部变量xy鼠标坐标.

如果您创建motion一个类方法,那么您可以设置实例属性self.xself.y鼠标坐标,然后可以从其他类方法访问它们.


小智 5

就个人而言,我更喜欢使用pyautogui,甚至与 Tkinter 结合使用。它不仅限于 Tkinter 应用程序,还可以在整个屏幕上运行,甚至在双屏配置下也是如此。

    import pyautogui
    x, y = pyautogui.position()
Run Code Online (Sandbox Code Playgroud)

如果您想保存各种位置,请添加点击事件。
我知道原来的问题是关于 Tkinter 的。


Tyl*_*lva 5

我想改进 Bryan 的答案,因为这仅在您有 1 台显示器时才有效,但如果您有多个显示器,它将始终使用您相对于主显示器的坐标。为了找到它相对于两台显示器,并获得准确的位置,然后使用vroot, 而不是root,像这样

root = tk.Tk()
...
x = root.winfo_pointerx()
y = root.winfo_pointery()
abs_coord_x = root.winfo_pointerx() - root.winfo_vrootx()
abs_coord_y = root.winfo_pointery() - root.winfo_vrooty()
Run Code Online (Sandbox Code Playgroud)