Home > OS >  tkinter: How can I remove labels created by for loops?
tkinter: How can I remove labels created by for loops?

Time:07-26

I have a list of data called data and I used a for loop to display the data in the GUI

for i in range(len(data)):
    data_label = Label(root, text=data[i])
    data_label.grid(row=i, column=0)

I tried to create a button which aims to remove all the labels by clicking the button as illustrated in this photo GUI Image. However, only the last data (which is 9) is removed. I would like to know how to remove all the data by clicking the button. I guess it's becuase the data_label only refer to the last data at the end of the for loop but I didn't know how to make the data_label

Here's the whole code:

from tkinter import *
root = tk.Tk()

data = [1, 3, 5, 7, 9]

for i in range(len(data)):
    data_label = Label(root, text=data[i])
    data_label.grid(row=i, column=0)

def remove_label():
    data_label["text"] = ""

button = Button(root, text="Remove", command=remove_label)
button.grid(row=0, column=1)

root.mainloop()

CodePudding user response:

Append your labels to a list and then loop over the list to delete text:

from tkinter import *
root = tk.Tk()

data = [1, 3, 5, 7, 9]

data_labels = []

for i in range(len(data)):
    data_label = Label(root, text=data[i])
    data_label.grid(row=i, column=0)
    data_labels.append(data_label)

def remove_label():
    for data_label in data_labels:
        data_label["text"] = ""

button = Button(root, text="Remove", command=remove_label)
button.grid(row=0, column=1)

root.mainloop()

CodePudding user response:

You can do it by taking advantage of the fact that the tkinter grid geometry manager, keeps track of the row and column location of all the widgets under its control. This means you can get the information 0needed from it instead of keeping track of it yourself (in some situations, like this one). You can get the grid information about a particular widget by calling its grid_info() method.

This illustrates what I am talking about:

from tkinter import *
root = Tk()

data = [1, 3, 5, 7, 9]

for i in range(len(data)):
    data_label = Label(root, text=data[i])
    data_label.grid(row=i 1, column=0)

def remove_data_labels():
    col = data_label.grid_info()['column']  # Column data_labels are in.
    # Create list of all the widgets in this same column.
    widgets = data_label.master.grid_slaves(column=col)
    # Remove the text from all the Labels in same column.
    for widget in widgets:
        if isinstance(widget, Label):
            widget.config(text='')

button = Button(root, text="Remove", command=remove_data_labels)
button.grid(row=0, column=1)

root.mainloop()

CodePudding user response:

Change the remove_label function to:

def remove_label():
    for i in range(len(data)):
        data_label = Label(root, text="")
        
  • Related