2014-04-08 211 views
12

有沒有辦法獲得鼠標的位置並將其設置爲var?鼠標位置Python Tkinter

+0

參見:獲得使用Python活動窗口(HTTP: //stackoverflow.com/q/10266281/562769) –

回答

15

你可以建立一個回調到<Motion>事件作出反應:

import Tkinter as tk 
root = tk.Tk() 

def motion(event): 
    x, y = event.x, event.y 
    print('{}, {}'.format(x, y)) 

root.bind('<Motion>', motion) 
root.mainloop() 

我不知道你想要什麼樣的變量。上面,我將局部變量xy設置爲鼠標座標。

如果您製作motion類方法,則可以將實例屬性self.xself.y設置爲鼠標座標,然後可以從其他類方法訪問該座標。

+0

我可以將它作爲var返回嗎? – Kpfromer

+0

好吧,沒有任何東西會收到回調函數的返回值,所以從'motion'返回它是沒有用的。 – unutbu

+0

我可以在函數中設置x,y作爲var嗎? – Kpfromer

16

在任何時間點,您都可以使用方法winfo_pointerxwinfo_pointery來獲取相對於根窗口的x,y座標。將其轉換成絕對的屏幕座標就可以得到winfo_pointerxwinfo_pointery,並從減去相應的winfo_rootxwinfo_rooty

例如:

root = tk.Tk() 
... 
x = root.winfo_pointerx() 
y = root.winfo_pointery() 
abs_coord_x = root.winfo_pointerx() - root.winfo_rootx() 
abs_coord_y = root.winfo_pointery() - root.winfo_rooty() 
+0

當您想要獲取從頂級抓取內部單擊的ttk :: notebook選項卡的tab_id(筆記本在頂級小部件的外部)時,這非常方便。 – Kumba

+1

這似乎是更好的答案。 – Haboryme