On radio buttons in tkinter

Christian Gollwitzer auriocus at gmx.de
Sat Jan 4 06:23:27 EST 2014


Am 04.01.14 11:17, schrieb eneskristo at gmail.com:
> So the issue is like this. I have to make a 2 x N grid like this:
> o Radio - 1 o Radio - 2
> o Radio - 3 o Radio - 4
> ...
> o Radio - N - 1 o Radio - N
>
> How to do so with a loop?
>

Create the buttons and append them into a list, so you can later refer 
to them. Use grid() to create the layout you want (the text widget is an 
alternative) Make sure you set the same variable and different "values", 
so that the radiobuttons can distinguish which one is selected. The rule 
is:

1) If the associated variable has the value of "value", the button is 
selected

2) If the associated variable has a different value, the button is not 
selected (thus you can implement selecting nothing by setting the 
variable to some bogus value)

3) For Ttk widgets: If the variable is undefined, the button is in the 
third state

I'm not sure Tkinter handles case 3, because if you delete the variable 
object by letting it go out of scope, there is probably no way to 
reattach it to the buttons. And there is no unset method, let alone a 
translation from unset variables to None if you do it by bypassing Tkinter:

Apfelkiste:~ chris$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> import Tkinter
 >>> t=Tkinter.Tk()
 >>> s=Tkinter.StringVar()
 >>> s.set('Hello')
 >>> s.get()
'Hello'
 >>> t.eval('unset ' + str(s))
''
 >>> s.get()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", 
line 255, in get
     value = self._tk.globalgetvar(self._name)
_tkinter.TclError: can't read "PY_VAR0": no such variable
 >>>


IMHO the last call should translate an unset variable to None to by 
useful for three-state widgets. You can still do it manually by invoking 
the widget's state() method

	Christian



More information about the Python-list mailing list