2011-05-23 20 views
4

我試圖使用grid_location方法,從網格幾何經理,在Tkinter的,但似乎我做錯了。按鈕有根據「grid_location」的方法自己的座標系?

這裏是我的代碼:

from tkinter import * 


root = Tk() 

b=Button(root, text="00") 
b.grid(row=0, column=0) 
b2=Button(root, text="11") 
b2.grid(row=1, column=1) 
b3=Button(root, text="22") 
b3.grid(row=2, column=2) 
b4=Button(root, text="33") 
b4.grid(row=3, column=3) 
b5=Button(root, text="44") 
b5.grid(row=4, column=4) 

def mouse(event): 
    print(event.x, event.y) 
    print(root.grid_location(event.x, event.y)) 

root.bind("<Button-1>", mouse) 

root.mainloop() 

當我點擊按鈕之外,它的工作原理,但是當我點擊任何按鈕裏面,似乎每個按鈕都有自己的座標系。因此,儘管代碼中的每個按鈕都位於(0,0)單元格中,但它們都位於常規網格中。

回答

6

你是正確的,每個按鈕「有它自己的座標系」。更準確地,雖然,event.xevent.y值是相對於與所述事件而不是控件的父或根窗口相關聯的窗口小部件。

如果你真的需要的行和列的小部件是可以使用grid_info獲得與該事件相關的窗口小部件的行和列。例如:

def mouse(event): 
    grid_info = event.widget.grid_info() 
    print("row:", grid_info["row"], "column:", grid_info["column"]) 
+0

謝謝布萊恩,工作完美。我之前嘗試過get_info,但不知道如何使用它。很好的解釋。 – 2011-05-23 21:04:32

相關問題