gpt4 book ai didi

python - 在 tkinter 中获取光标的绝对位置

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:57 25 4
gpt4 key购买 nike

所以我从我的主管那里得到了一个代码,我在理解方面遇到了问题。我希望使用 create_rectangle 方法在光标所在的位置绘制一个矩形,我为其提供参数/坐标:

rect = create_rectangle(x, y, x + 10, y + 10, fill = 'blue', width = 0)

我希望这里的 xy 是我的光标相对于我的根窗口的当前坐标。

xy 在将它们传递给此函数之前在我的代码中计算的方式是:

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

反射(reflect)鼠标指针的绝对位置,与 winfo_pointerx()w.winfo_pointery()(或 w.winfo_pointerxy() )形成对比,后者反射(reflect)鼠标指针相对于您的坐标w 的根窗口

但是绝对和相对概念是什么意思?

winfo_rootx()winfo_rooty()分别返回左上角的xy坐标根窗口上此小部件的一角。 但是这些 xy 坐标是根据您笔记本电脑的屏幕计算的

winfo_pointerx()winfo_pointery() 返回鼠标指针相对于主 根窗口 的 x 和 y 坐标,而不是屏幕

因此,通过仅运行 winfo_pointerxy(),您只考虑了 根窗口 本身,而您忽略了 其余部分(< strong>屏幕)。

但问题是,当您将鼠标移到根窗口上时,您不能忘记您的系统正在根据笔记本电脑的屏幕计算坐标。

替代方法

请注意,您可以替换当前代码:

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

关于python - 在 tkinter 中获取光标的绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com