Home > database >  Tkinter how to grid() successively with oop
Tkinter how to grid() successively with oop

Time:04-04

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)

CodePudding user response:

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)

CodePudding user response:

When a new instance of the Team class is created, you could pass the row as a parameter. And then, you can use that value in the .grid statement.

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)
  • Related