user3064033
user3064033

Reputation: 25

How do I delete a python tkinter label based on condition?

I am going to use pseudo-code because my real code is a lot messier. Basically I have a code that looks like this:

if i>0 and B!=1:
  #display label #1 using .grid
elif: i<0 and B!=1 :
  #display label #2 but on the same place as label#1

So I end up with both labels on top of each other. How do I get one of the labels to be

removed before the other label is displayed?

EDIT: Note that my program will also run in an infinite loop so both labels will be displayed through out the program's run.

Upvotes: 1

Views: 1297

Answers (1)

Deelaka
Deelaka

Reputation: 13721

Use the widget.destroy() method to destroy label1:

if i>0 and B!=1:
    label1 = Tk.Label(root,text='Label1')
    label1.grid(row = 2,column=5)

elif i<0 and B!=1:
    if 'label1' in globals():
        label1.destroy()
    label2 = Tk.Label(root,text='Label2')
    label2.grid(row = 2,column=5)

EDIT:

Note you could use:

if 'label1' in globals():
    label1.destroy()

To avoid a local variable "label1" refrence before assignment Error

Upvotes: 2

Related Questions