2016-03-03 52 views
0

我目前正在用TkInter製作一個GUI,GUI由構建在for循環中的網格組成,其中1個變量用於所有按鈕(它在每個循環都得到更新)。 我想知道如何獲得我按下的任何按鈕的座標。 (例如,當我按下時,按鈕在網格上給出它的座標)我使用了grid_info,但它只獲取了最後一個創建的按鈕的信息。 感謝您的幫助:)TkInter網格上的按鈕座標

回答

2

您可以將行和列傳遞給與該函數關聯的命令。最常用的兩種方法是使用lambda或functools.partial。

下面是使用lambda一個例子:

import tkinter as tk 

def click(row, col): 
    label.configure(text="you clicked row %s column %s" % (row, col)) 

root = tk.Tk() 
for row in range(10): 
    for col in range(10): 
     button = tk.Button(root, text="%s,%s" % (row, col), 
          command=lambda row=row, col=col: click(row, col)) 
     button.grid(row=row, column=col, sticky="nsew") 
label = tk.Label(root, text="") 
label.grid(row=10, column=0, columnspan=10, sticky="new") 

root.grid_rowconfigure(10, weight=1) 
root.grid_columnconfigure(10, weight=1) 

root.mainloop()