[英]Getting the absolute position of cursor in tkinter
因此,我从主管那里得到了一个代码,我在理解时遇到了问题。 我希望使用create_rectangle
方法为我的光标绘制一个矩形,为此我将参数/坐标指定为:
rect = create_rectangle(x, y, x + 10, y + 10, fill = 'blue', width = 0)
我希望这里的x
和y
是我的光标相对于根窗口的当前坐标。
在我的代码中将x
和y
传递给此函数之前,它们的计算方式是:
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
而且我无法终生理解为什么这样做。 我只是尝试做
x = root.winfo_pointerx()
y = root.winfo_pointery()
而且也
x = root.winfo_rootx()
y = root.winfo_rooty()
但它们都不在光标所在的位置绘制矩形。 我也尝试查看文档,但无法真正理解正在发生的事情。
那么,为什么在这里执行x = root.winfo_pointerx() - root.winfo_rootx()
和y = root.winfo_pointery() - root.winfo_rooty()
?
您正在询问绝对屏幕和相对鼠标指针位置之间的差异。
表示法:
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
与winfo_pointerx()
和w.winfo_pointery()
(或w.winfo_pointerxy()
)形成对比, winfo_pointerx()
反映了鼠标指针的绝对位置,后者相对于w
的根窗口反映了鼠标指针的坐标。
但是,绝对和相对概念是什么意思?
winfo_rootx()
和winfo_rooty()
分别返回此窗口小部件在根窗口左上角的x
和y
坐标。 但是这些x
和y
坐标是根据笔记本电脑的屏幕计算的
winfo_pointerx()
和winfo_pointery()
返回相对于主根窗口的鼠标指针的x和y坐标,而不是返回到SCREEN的坐标。
因此,仅运行winfo_pointerxy()
仅考虑根窗口本身,而忽略其余窗口 ( SCREEN )。
但是问题在于,当您在根窗口上移动鼠标时,您一定不要忘记您的系统正在根据便携式计算机的SCREEN计算坐标。
请注意,您可以替换当前的代码:
def get_absolute_position(event=None):
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
return x, y
通过利用事件坐标的其他方法:
def get_absolute_position(event):
x = event.x
y = event.y
return x, y
简单:
from tkinter import *
root = Tk()
def f(event):
print(event.x, event.y)
root.bind("<Motion>", f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.