我正在使用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