Checkbutton Value Constant
I am trying to set a value to the checkbutton by passing 1 or 0 (as an integer) to this function. However, there is no change in state of checkbutton. Please help. def change_O
Solution 1:
Probably problem is because CheckVar1
is local variable and it doesn't exist when you leave function.
Use global variable and it will work.
from tkinter import *
# --- functions ---
def change_On_Off_state(*args):
CheckVar1.set(*args)
OnOff = Checkbutton(root, text="On", variable=CheckVar1, onvalue=1, offvalue=0, height=1, width=10, anchor=W, bg='Light Blue')
OnOff.grid(row=4, column=2, padx=10, sticky=W)
#CheckVar1.trace_variable("w", On_Off_state)
# --- main ----
root = Tk()
CheckVar1 = IntVar() # global
change_On_Off_state(1)
# "start the engine"
root.mainloop()
I think you don't have to create new Checkbutton()
to change state. Create Checkbutton
and CheckVar
only once and use only `CheckVar1.set(...) many times.
from tkinter import *
# --- functions ---defchange_On_Off_state(*args):
CheckVar1.set(*args)
#CheckVar1.trace_variable("w", On_Off_state)defchange_on_button_press():
if CheckVar1.get() == 1:
CheckVar1.set(0)
else:
CheckVar1.set(1)
# --- main ----
root = Tk()
# create only once
CheckVar1 = IntVar() # global# create only once
OnOff = Checkbutton(root, text="On", variable=CheckVar1, onvalue=1, offvalue=0)
OnOff.grid()
# use many times
change_On_Off_state(1)
# use button to on/off checkbutton
btn = Button(root, text="On / Off", command=change_on_button_press)
btn.grid()
# "start the engine"
root.mainloop()
Post a Comment for "Checkbutton Value Constant"