1 回答

TA貢獻1878條經驗 獲得超4個贊
如果您打算在創建一個小部件并將其添加到您的界面后對其進行任何操作,最好保留一個參考。
這是對您的代碼的修改,它創建了一個字典button_dict來存儲您的每個按鈕。鍵是元組(row,column)。我將button_dict作為附加輸入添加到您的click函數中,并修改了按鈕綁定以使用 包含這個新輸入lambda。
import tkinter
def click(event,button_dict):
space = event.widget
space_label = space['text']
row = space.grid_info()['row'] #get the row of clicked button
column = space.grid_info()['column'] #get the column of clicked button
button = button_dict[(row,column)] # Retrieve our button using the row/col
print(button['text']) # Print button text for demonstration
board = tkinter.Tk()
button_dict = {} # Store your button references here
for i in range(0,9): #creates the 3x3 grid of buttons
button = tkinter.Button(text = i) # Changed the text for demonstration
if i in range(0,3):
r = 0
elif i in range(3,6):
r = 1
else:
r = 2
button.grid(row = r, column = i%3)
button.bind("<Button-1>",lambda event: click(event,button_dict))
button_dict[(r,i%3)] = button # Add reference to your button dictionary
board.mainloop()
如果您只對按下的按鈕感興趣,您可以簡單地訪問該event.widget屬性。從你的例子來看,聽起來你想修改每個事件的任意數量的按鈕,所以我認為字典會給你更多的通用性。
添加回答
舉報