Reputation: 23
this is the first question I am posting here. I recently created a window in Tkinter that contains a frame. After clicking a button a label containing text should appear inside the frame. When clicking the button again - the label should disappear. It works fine until I click the button for a third time to call the label inside the frame again.
Here is the code:
from tkinter import *
root=Tk()
root.geometry("500x500+100+100")
root.title("Switch label")
root.resizable(False,False)
is_off=True
def label_disappear():
global label
global is_off
label.destroy()
button.config(text="Add",command=label_appear)
is_off=True
def label_appear():
global label
global is_off
if is_off:
label.place(x=20,y=20)
button.config(text="Remove",command=label_disappear)
is_off=False
else:
label_disappear()
frame=Frame(root,bg="light green",width=460,height=200)
frame.place(x=20,y=20)
label=Label(frame,text="This is label",bg="light green")
button=Button(root,text="Add",command=label_appear)
button.place(relx=0.5,y=250,anchor="center")
root.mainloop()
and here is the error that PyCharm throws:
How can I change it so that it works as a real switch and not only as one time on/off button?
Thank you in advance!
Upvotes: 0
Views: 428
Reputation: 46669
It is because you have destroyed the label inside label_disappear()
. If you want the label to be shown again, replace label.destroy()
by label.place_forget()
inside label_disappear()
:
def label_disappear():
global label
global is_off
label.place_forget() # don't destroy the label, just make it invisible
button.config(text="Add",command=label_appear)
is_off=True
Upvotes: 1