Search code examples
pythontkintertkinter-entry

Remove whole Entry row (5 boxes) in tkinter


I have button and a function which creates 5 Entry boxes in newline every time you click it

def __init__(self, master):
    [...]
    self.rows_list = 2
    self.new_button = ttk.Button(self.tab1, text='Add', command=self.new_window).grid(column=5, row=0)

def new_window(self):
    rows = self.rows_list
    labels = 5
    for x in range(labels):
        ttk.Entry(self.tab1).grid(column=int(x), row=rows)
    self.rows_list += 1

I am struggling with making REMOVE button removing last row. Tried multiple "internet solutions" but non of them helped.


Solution

  • For your case, since you have self.row_list to be used as the next row that those new entries be created, you can use this variable to get the widgets in the last row and destroy them:

        def __init__(self, master):
            ...
    
            self.rows_list = 2
            ttk.Button(self.tab1, text='Add', command=self.new_window).grid(column=5, row=0)
            ttk.Button(self.tab1, text='Remove', command=self.remove_row).grid(column=6, row=0)
    
        ...
    
        def remove_row(self):
            if self.rows_list > 2:
                # get widgets in last row
                widgets = self.tab1.grid_slaves(row=self.rows_list-1)
                # and destroy them
                for w in widgets:
                    w.destroy()
                # update self.rows_list
                self.rows_list -= 1
    

    Note that this solution is based on the posted code, if there are other widgets in the same row of those entries, it may not work.