我正在使用tkinter創建一個8x8按鈕矩陣,當按下單個按鈕時添加到最終列表(例如finalList =((0,0),(5,7),( 6,6),...),允許我快速創建8x8(x,y)座標圖像。我已經創建了帶有按鈕的窗口,但現在嘗試在函數中引用這些按鈕以添加到列表甚至改變按鈕的顏色tkinter多個按鈕顏色變化
我已經讀過,一旦按鈕被創建,你創建另一個它將移動到該按鈕引用我懷疑我需要使用一個字典或二維數組來存儲所有這些引用但我正努力想出一個解決方案。
from tkinter import *
class App:
def updateChange(self):
'''
-Have the button change colour when pressed
-add coordinate to final list
'''
x , y = self.xY
self.buttons[x][y].configure(bg="#000000")
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.buttons = [] # Do I need to create a dict of button's so I can reference the particular button I wish to update?
for matrixColumn in range(8):
for matrixRow in range(8):
self.xY = (matrixColumn,matrixRow)
stringXY = str(self.xY)
self.button = Button(frame,text=stringXY, fg="#000000", bg="#ffffff", command = self.updateChange).grid(row=matrixRow,column=matrixColumn)
self.buttons[matrixColumn][matrixRow].append(self.button)
root = Tk()
app = App(root)
root.mainloop()
感謝您的幫助,使用了第二個例子,它發揮了魅力。真的很感謝幫助,希望我能自己管理其餘的想法。肯定會從中學習! – SgtSafety