C.Mannerstråle C.Mannerstråle - 12 days ago 6
Python Question

Trying to ...".pack_forget()" all items from a looped list

I have this code inside my method:

class Graphics:
def __init__(self, root):
root.geometry("640x640")
root.title("Hello")
root.configure(bg = "black")

self.scoreButton = Button(root, text = "See Score", command = self.score)
self.HomeButton = Button(root, text = "Menu", command = self.deleteScore)

def score(self):
for i,e in enumerate(self.myList, start=1):
if e == "10":
self.seeScore = Label(text = "Times played: " + str(i) + " - Loss", bg="black", fg="white", font = ("Arial", 15))
self.seeScore.pack()
else:
self.seeScore = Label(text = "Times played " + str(i) + "Score: " + str(e), bg="black", fg="white", font = ("Arial", 15))
self.seeScore.pack()

def deleteScore(self):
self.seeScore.pack_forget()


As of right now it only forgets the last item when i run the method but i want it to forget all the items... I cant figure out how to do this. Can anyone please help me?

Answer

If you want to delete or hide a list of widgets, you have to actually store the widgets in a list.

Example

self.labels = []
for i,e in enumerate(self.myList, start=1):                                               
    if e == "10":
        label = Label(text = str(i), bg="black", fg="white", font = ("Arial", 15))
        self.HelloWorld.pack()
    else:                                           
        label = Label(text = str(i) + str(e), bg="black", fg="white", font = ("Arial", 15))
        self.HellowWorld.pack()
    self.labels.append(label)

...

def deleteHelloWorld(self):
    for widget in self.labels:
        widget.pack_forget()