2

So I'm trying to delete labels when a button is clicked, but I get an error on doing so.

This is a loop that generates labels based on the list that I have declared earlier.

    t = 150
    i = 0
    for p in products_list:
        self.pr1 = Label(self.right, text=str(products_list[i]), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=0, y=t)
        self.pr2 = Label(self.right, text=(str(quantity_list[i])), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=130, y=t)
        self.pr3 = Label(self.right, text=(str(price_list[i])), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=240, y=t)
        t += 40
        i += 1

Now I'm trying to delete those labels when I click a button. I have created a print_bill function which has to delete the labels. I tried:

def print_bill(self):
    f = open(str(date), "w+")
    f.write("Bill Bill Bill")
    f.close()

    tkinter.messagebox.showinfo("Bill", "Bill Generated Successfully")
    self.pr1.destroy()
Bibek Bhandari
  • 422
  • 1
  • 4
  • 15

1 Answers1

0

Your problem is this line:

self.pr1 = Label(...).place(x=0, y=t)

What you're basiclly doing in this line, is creating a Label object, calling .place on that object in-place, and then assigning the result of the method to self.pr1. Since Label.place returns, None, self.pr1 is assigned to None.

You need to call the .place method on the label object, after assigning it to self.pr1. Otherwise, you loose all references to the Label object created and it's destroyed.

self.pr1 = Label(...)
self.pr1.place(x=0, y=t)

In other words, Label.place doesn't work in-place. After doing it's work, it returns no references to the object it was called on.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
  • Thanks it worked, but how do I delete the labels generated from that loop. The destroy() method works but deletes only the last generated label. Is there any way I can delete all the labels? – Bibek Bhandari Jan 17 '18 at 02:52
  • You have to call `destory` on each `Label` object, @BibekBhandari. – Christian Dean Jan 17 '18 at 02:54