簡體   English   中英

獲取光標在tkinter中的絕對位置

[英]Getting the absolute position of cursor in tkinter

因此,我從主管那里得到了一個代碼,我在理解時遇到了問題。 我希望使用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()

winfo_pointerx()w.winfo_pointery() (或w.winfo_pointerxy() )形成對比, winfo_pointerx()反映了鼠標指針的絕對位置,后者相對於w的根窗口反映了鼠標指針的坐標。

但是,絕對和相對概念是什么意思?

winfo_rootx()winfo_rooty()分別返回此窗口小部件在根窗口左上角的xy坐標。 但是這些xy坐標是根據筆記本電腦的屏幕計算的

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM