leb*_*ski 1 python canvas tkinter tkinter-canvas
所以我从我的主管那里得到了一个代码,我在理解方面遇到了问题。我希望使用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()
Run Code Online (Sandbox Code Playgroud)
我一生都无法理解为什么要这样做。我试着做
x = root.winfo_pointerx()
y = root.winfo_pointery()
Run Code Online (Sandbox Code Playgroud)
而且也只是
x = root.winfo_rootx()
y = root.winfo_rooty()
Run Code Online (Sandbox Code Playgroud)
但这些都没有绘制光标所在的矩形。我也尝试查看文档,但无法真正理解发生了什么。
那么,为什么x = root.winfo_pointerx() - root.winfo_rootx()和y = root.winfo_pointery() - root.winfo_rooty()正在这里做什么?
您问的是绝对 SCREEN和相对鼠标指针位置之间的区别。
符号:
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
Run Code Online (Sandbox Code Playgroud)
反映鼠标指针的绝对位置,而winfo_pointerx()和w.winfo_pointery()(或w.winfo_pointerxy())则反映鼠标指针相对于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
Run Code Online (Sandbox Code Playgroud)
通过利用事件坐标的另一种方法:
def get_absolute_position(event):
x = event.x
y = event.y
return x, y
Run Code Online (Sandbox Code Playgroud)