Reputation: 13
I have a label that is coded like this that contains text that is set upon running the program.
label_text = StringVar()
label = Label(window,textvariable=label_text)
label_text.set("Off")
I also have a checkbox;
var= IntVar()
Check= Checkbutton(window,text = "On",variable = var,onvalue = 1,offvalue = 0)
These are both packed like this:
label.pack()
Check.pack(side="left")
When the checkbox is checked, I want to have the label change text to "On", something like this.
if var.get()==1:
label_text.set("On")
The text remains at Off when I check the checkbox. Any help would be appreciated.
Upvotes: 0
Views: 3517
Reputation: 16169
There are several ways of updating the label text when the checkbutton state changes.
One possibility is to make the label and the checkbutton share the same StringVar
and set the onvalue/offvalue of the checkbutton to "On"/"Off". That way, when the state of the checkbutton changes, the text of the label is automatically updated.
from tkinter import StringVar, Tk, Label, Checkbutton
window = Tk()
label_text = StringVar()
label = Label(window, textvariable=label_text)
label_text.set("Off")
check= Checkbutton(window, text="On", variable=label_text,
onvalue="On", offvalue="Off")
label.pack()
check.pack(side="left")
window.mainloop()
If for some reason you really want the onvalue/offvalue of the checkbutton to be 0/1, you can pass a function to the command
option of the checkbutton. This function will change the text of the label depending on the state of the checkbutton.
from tkinter import StringVar, Tk, Label, Checkbutton, IntVar
def update_label():
if var.get() == 1:
label_text.set("On")
else:
label_text.set("Off")
window = Tk()
label_text = StringVar()
label = Label(window, textvariable=label_text)
label_text.set("Off")
var = IntVar()
check= Checkbutton(window, text="On", variable=var,
onvalue=1, offvalue=0, command=update_label)
label.pack()
check.pack(side="left")
window.mainloop()
Upvotes: 1