[英]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.