Tkinter checkbuttons and variables

Eric Brunel eric_brunel at despammed.com
Wed Feb 21 10:34:50 EST 2007


On Wed, 21 Feb 2007 15:50:57 +0100, Gigs_ <gigs at hi.t-com.hr> wrote:
> from Tkinter import *
>
> states = []
>
> def onpress(i):
>      states[i] = not states[i]
>
>
> root = Tk()
> for i in range(10):
>      chk = Checkbutton(root, text= str(i), command=lambda i=i:  
> onpress(i))
>      chk.pack(side=LEFT)
>      states.append(0)
> root.mainloop()
> print states
>
> after exiting i get everything like it suppose to but when i put command  
> like this:
> command=lambda: onpress(i)
> i got only last checkbutton check.
>
> Why i have to pass this default argument?

I'm basically not answering your question here, but the usual way to get a  
checkbuttons's state is as follows:

states = []
root = Tk()
for i in range(10):
   stateVar = BooleanVar()
   chk = Checkbutton(root, text=str(i), variable=stateVar)
   chk.pack(side=LEFT)
   states.append(stateVar)
root.mainloop()
print [v.get() for v in states]

If you want to get the value of one of your states, use the get() method  
on BooleanVar. If you want to change such a state, use the set(value)  
method.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"



More information about the Python-list mailing list