tkinter 多个按钮颜色变化

tkinter Multiple Buttons Colour Change

我正在使用 tkinter 创建一个 8x8 按钮矩阵,当按下各个按钮时,它会添加到最终列表(例如 finalList = ((0,0),(5,7),(6,6 ), ...), 允许我快速创建 8x8 (x,y) 坐标图像。我已经使用按钮创建了 window 但现在在尝试在要添加到的函数中引用这些按钮时遇到问题列表甚至更改按钮的颜色

我已经读到,一旦创建了按钮并且您创建了另一个按钮,它就会移动到该按钮引用。我怀疑我需要使用字典或二维数组来存储所有这些按钮引用,但我正在努力寻找解决方案。

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()

Example of the 8x8 Matrix

self.xY 在双 for 循环中设置为 7,7 且从未更改。如果您希望每个按钮都不同,您可能需要更改 updateChange 以获取两个参数 (x,y),并使用类似的方法将它们作为按钮的命令传入; lambda x=matrixColumn y=matrixRow: self.updateChange(x,y)

示例updateChange

def updateChange(self, x, y):
    '''...'''
    self.buttons[x][y].configure(bg="black")

下面是 2 个示例,第一个是如果您只想更改颜色而不想更改其他内容,那么您可以不使用列表来完成。第二个涉及使用列表并演示 Delioth 指出的内容

class App(object):
    def __init__(self, master):
        self._master = master

        for col in range(8):
            for row in range(8):
                btn = tk.Button(master, text = '(%d, %d)' % (col, row), bg = 'white')
                btn['command'] = lambda b = btn: b.config(bg = 'black')
                btn.grid(row = row, column = col)

class App(object):
    def __init__(self, master):
        self._master = master
        self._btn_matrix = []

        for col in range(8):
            row_matrix = []
            for row in range(8):
                btn = tk.Button(master, text = '(%d, %d)' % (col, row), bg = 'white',
                                command = lambda x = row, y = col: self.update(x, y))
                btn.grid(row = row, column = col)
                row_matrix.append(btn)
            self._btn_matrix.append(row_matrix)

    def update(self, row, col):
        self._btn_matrix[col][row].config( bg = 'black' )

if __name__ == '__main__':
    root = tk.Tk()
    app = App(root)
    root.mainloop()