Tkinter 如何使用 oop 连续网格()

Tkinter how to grid() successively with oop

我正在制作一个简单的游戏。当我调用它 class 时,我希望它将 3 个小部件放在同一行,但是当我创建一个新实例时,我希望使用 grid() 方法将同一组小部件放在下一行。做这个的最好方式是什么?我是一般编程的新手,尤其是 tkinter 和 OOP,所以非常感谢任何帮助(:

class Team:
    name = 'New team'
    players = []
    points = 0

    def __init__(self, master):
        self.btn_edit = tk.Button(master, text='Edit')
        self.btn_edit.grid(row=1, column=0)

        self.lbl_teamname = tk.Label(master, text='New team')
        self.lbl_teamname.grid(row=1, column=1)

        self.btn_remove = tk.Button(master, text='-')
        self.btn_remove.grid(row=1, column=2)


tk.Button(teams, text='+', command=lambda: Team(teams)).grid(row=0, column=0)

创建 Team class 的新实例时,您可以将 row 作为参数传递。然后,您可以在 .grid 语句中使用该值。

class Team:
    name = 'New team'
    players = []
    points = 0

    def __init__(self, master, row):
        self.btn_edit = tk.Button(master, text='Edit')
        self.btn_edit.grid(row=row, column=0)

        self.lbl_teamname = tk.Label(master, text='New team')
        self.lbl_teamname.grid(row=row, column=1)

        self.btn_remove = tk.Button(master, text='-')
        self.btn_remove.grid(row=row, column=2)


tk.Button(teams, text='+', command=lambda: Team(teams)).grid(row=0, column=0)

您可以通过container.grid_size() which returns(列,行)来获取容器中使用了多少行。然后可以将返回的rows作为.grid(...)row选项的值:

class Team:
    name = 'New team'
    players = []
    points = 0

    def __init__(self, master):
        cols, rows = master.grid_size() # return size of grid

        self.btn_edit = tk.Button(master, text='Edit')
        self.btn_edit.grid(row=rows, column=0)

        self.lbl_teamname = tk.Label(master, text='New team')
        self.lbl_teamname.grid(row=rows, column=1)

        self.btn_remove = tk.Button(master, text='-')
        self.btn_remove.grid(row=rows, column=2)