Search code examples
pythonooptkintertkinter-layout

Tkinter how to grid() successively with oop


I'm making a simple game. When I call this class I want it to place 3 widgets on the same row, but when I make a new instance I want the same group of widgets to place on the next row with the grid() method. What is the best way to do this? I'm new to programming in general, especially tkinter and OOP so any help is much appreciated (:

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)

Solution

  • You can get how many rows are used in a container by container.grid_size() which returns (columns, rows). Then you can use the returned rows as the value of the row option of .grid(...):

    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)