使用按钮为我的 tkinter window 压缩我的 class

Compacting my class for my tkinter window with buttons

我有一个问题,我可以压缩这段代码(有人告诉我可以)但是在这样做时没有得到任何帮助,也不知道如何去做。

尝试将它放入 for 循环中,但我想要一个 3x3 的按钮网格,中间的按钮是列表框,按钮的死点。

我环顾四周,一个小时后,我没有得到任何答复。

在这里,我尝试将每个按钮附加到一个列表并将它们打包在一个 for 循环中,但是是否可以在一个 for 循环中分别完成它们,然后分别完成和打包列表框?

class MatchGame(Toplevel):
    def __init__(self,master):
        self.fr=Toplevel(master)
        self.GameFrame=Frame(self.fr)
        self.AllButtons=[]
        self.AllButtons.append(Button(self.GameFrame,bg="red",height=5,width=15,text=""))
        self.AllButtons.append(Button(self.GameFrame,bg="green",height=5,width=15,text=""))
        self.AllButtons.append(Button(self.GameFrame,bg="dark blue",height=5,width=15,text=""))
        self.AllButtons.append(Button(self.GameFrame,bg="turquoise",height=5,width=15,text=""))
        self.AllButtons.append(Listbox(self.GameFrame,bg="grey",height=5,width=15))
        self.AllButtons.append(Button(self.GameFrame,bg="yellow",height=5,width=15,text=""))
        self.AllButtons.append(Button(self.GameFrame,bg="pink",height=5,width=15,text=""))
        self.AllButtons.append(Button(self.GameFrame,bg="orange",height=5,width=15,text=""))
        self.AllButtons.append(Button(self.GameFrame,bg="purple",height=5,width=15,text=""))
        for x in range(0,len(self.AllButtons)):
            AllButtons[x].grid(row=int(round(((x+1)/3)+0.5)),column=x%3)
        self.GameFrame.grid(row=0,column=0)
        Quit=Button(self.fr, text="Destroy This Game", bg="orange",command=self.fr.destroy)
        Quit.grid(row=1,column=0)

它需要有独立的颜色、相同的尺寸等等,但我不知道该怎么做。我是 类 的新手,我一辈子都想不出如何用紧凑的代码制作这个 window(不是每个对象 9 行,然后将它们全部打包。)

如果您想动态创建一个 3x3 的按钮网格。那么嵌套的 for 循环似乎是您的最佳选择。

示例:

import tkinter as tk

root = tk.Tk()
# List of your colours
COLOURS = [['red', 'green', 'dark blue'],
           ['turquoise', 'grey', 'yellow'],
           ['pink', 'orange', 'purple']]

# Nested for-loop for a 3x3 grid
for x in range(3):
    for y in range(3):        
        if x == 1 and y == 1: # If statement for the Listbox
            tk.Listbox(root, bg = COLOURS[x][y], height=5, width=15).grid(row = x, column = y)
        else:
            tk.Button(root, bg = COLOURS[x][y], height=5, width=15).grid(row = x, column = y)

root.mainloop()