[Tutor] Checkbox problem in Tkinter
Peter Otten
__peter__ at web.de
Mon Jan 10 12:35:40 CET 2011
Alan Gauld wrote:
>
> "ANKUR AGGARWAL" <coolankur2006 at gmail.com> wrote
>
>> from Tkinter import *
>> root=Tk()
>> var=StringVar()
>>
c=Checkbutton(root,text="hello",variable=var,onvalue="hhhh",offvalue="gggg")
>> c.pack()
>> root.mainloop()
>
> FWIW I get a different problem, namely that the var does not seem
> to get updated nor does changling the var seem to alter the buuttons
> state. But at least the button displays OK with 'hello' in the label
> and
> I can select/deselect it with the mouse. its just the change to the
> variable that is broken.
> If I write an explicit event handler:
>
> def f():
> var = 'hhhh' if var == 'gggg' else 'gggg'
>
> Then var changes OK. Here is my code(from Pythonwin):
>
>>>> def f(): global var; var = 'on' if var == 'off' else 'off';print
>>>> var
> ...
>>>> top = Tk()
>>>> var = StringVar()
>>>> c = Checkbutton(top,text='txt', variable=var, onvalue='on',
>>>> offvalue='off', command=f)
>>>> c.pack()
>>>> top.mainloop()
> off
> on
> off
> on
> off
> on
I think that is confusing. Tkinter is not supposed to rebind the global name
'var', it invokes its set() method. Try
from Tkinter import *
root = Tk()
var = StringVar()
def command():
print var.get()
cb = Checkbutton(root, text="yadda", onvalue="on", offvalue="off",
variable=var, command=command)
cb.pack()
root.mainloop()
You can also monitor changes to var's value directly:
from Tkinter import *
root = Tk()
var = StringVar()
def show(*args):
print var.get()
var.trace_variable('w', show)
cb = Checkbutton(root, text="yadda", onvalue="on", offvalue="off",
variable=var)
cb.pack()
root.mainloop()
More information about the Tutor
mailing list