1 回答

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您打算在創(chuàng)建一個(gè)小部件并將其添加到您的界面后對(duì)其進(jìn)行任何操作,最好保留一個(gè)參考。
這是對(duì)您的代碼的修改,它創(chuàng)建了一個(gè)字典button_dict來存儲(chǔ)您的每個(gè)按鈕。鍵是元組(row,column)。我將button_dict作為附加輸入添加到您的click函數(shù)中,并修改了按鈕綁定以使用 包含這個(gè)新輸入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()
如果您只對(duì)按下的按鈕感興趣,您可以簡(jiǎn)單地訪問該event.widget屬性。從你的例子來看,聽起來你想修改每個(gè)事件的任意數(shù)量的按鈕,所以我認(rèn)為字典會(huì)給你更多的通用性。
添加回答
舉報(bào)