Question

How would I go about forgetting a widget that was created by a for loop?

For example, I have this code here:

for getSong in a.findAll('name'):
        z += 1
        x += 1
        if z == 11:
            break
        else:
            text = ''.join(getSong.findAll(text=True))
            data = text.strip()
            songLab = Label(frame1, text=data)

Afterwards, the user presses a Button and it updates the widget, like so:

def update():
    try:
        openArtist.pack_forget()
        artistLab.pack_forget()
        songLab.pack_forget()
        getScrobbledTracksArtist()
    except NameError:
        getScrobbledTracksArtist()

The other widgets get removed by the one created in the for loop does not.

Example here:

Before updating widgets Before update

After updating widgets After update

As you can see, only one line of the widget was removed.

Edit

I tried doing the duplicate but it is not working for me. I made a list and made sure the labels were being added to the list, they are.

labels = []
for getSong in a.findAll('name'):
    z += 1
    x += 1
    if z == 11:
        break
    else:
        text = ''.join(getSong.findAll(text=True))
        data = text.strip()
        songLab = Label(frame1, text=data)
        labels.append(songLab)
        songLab.pack()

Then after a Button is pressed, the widgets update.

def update1():
try:
    openArtist.pack_forget()
    artistLab.pack_forget()
    labels[0].destroy()
    print labels
    getScrobbledTracksArtist()
except NameError:
    getScrobbledTracksArtist()

The labels are still in the list and are not being destroyed.

Was it helpful?

Solution

Like any other widget, you simply need to keep a reference to it. For example, you could append each widget to a list, then iterate over the list to remove the widgets.

Let's take a look at this code:

def update1():
    try:
        openArtist.pack_forget()
        artistLab.pack_forget()
        labels[0].destroy()
        print labels
        getScrobbledTracksArtist()
    except NameError:
        getScrobbledTracksArtist()

you are only ever deleting the first label in the list, and then you are failing to remove it from the list. What you need to do instead is to loop over the list, destroying each widget. Then you can reinitialize the list:

for label in labels:
    label.destroy()
labels = []

However, you have another problem in that it appears that labels may be a local variable. You will need to declare it as global so that the two different functions will be able to access and modify the list.

None of this is related to tkinter, this is simply how all python objects work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top