【问题标题】:Getting the absolute position of cursor in tkinter在 tkinter 中获取光标的绝对位置
【发布时间】:2016-07-18 04:26:59
【问题描述】:

所以我有一个来自我的主管的代码,我在理解上遇到了问题。我希望在我的光标所在的位置绘制一个矩形,使用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() 在这里完成?

【问题讨论】:

  • winfo_pointer() = 光标在屏幕上的位置。 winfo_root() = 窗口在屏幕上的位置。 winfo_pointer()-winfo_root() = 光标在窗口中的位置。

标签: python canvas tkinter tkinter-canvas


【解决方案1】:

您问的是绝对屏幕相对鼠标指针位置之间的区别。

符号:

x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()

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

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

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

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

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

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

替代方法

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

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

【讨论】:

    【解决方案2】:

    简单:

    from tkinter import *
    root = Tk()
    
    def f(event):
        print(event.x, event.y)
    
    root.bind("<Motion>", f)
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 2013-04-29
      • 1970-01-01
      • 2016-04-17
      相关资源
      最近更新 更多