Radio Buttons
Radio buttons are toggles too, but they are generally used in groups: just like the me-
chanical station selector pushbuttons on radios of times gone by, pressing one Radio
button widget in a group automatically deselects the one pressed last. In other words,
at most, only one can be selected at one time. In tkinter, associating all radio buttons
in a group with unique values and the same variable guarantees that, at most, only one
can ever be selected at a given time.
Like check buttons and normal buttons, radio buttons support a command option for
registering a callback to handle presses immediately. Like check buttons, radio buttons
also have a variable attribute for associating single-selection buttons in a group and
fetching the current selection at arbitrary times.
In addition, radio buttons have a value attribute that lets you tell tkinter what value
the button’s associated variable should have when the button is selected. Because more
than one radio button is associated with the same variable, you need to be explicit about
each button’s value (it’s not just a 1 or 0 toggle scenario). Example 8-25 demonstrates
radio button basics.
Example 8-25. PP4E\Gui\Tour\demoRadio.py
"create a group of radio buttons that launch dialog demos"
from tkinter import * # get base widget set
from dialogTable import demos # button callback handlers
from quitter import Quitter # attach a quit object to "me"
class Demo(Frame):
def init(self, parent=None, options):
Frame.init(self, parent, options)
self.pack()
Label(self, text="Radio demos").pack(side=TOP)
self.var = StringVar()
for key in demos:
Radiobutton(self, text=key,
command=self.onPress,
variable=self.var,
value=key).pack(anchor=NW)
self.var.set(key) # select last to start
Button(self, text='State', command=self.report).pack(fill=X)
Quitter(self).pack(fill=X)
def onPress(self):
pick = self.var.get()
print('you pressed', pick)
print('result:', demos[pick]())
def report(self):
print(self.var.get())
if name == 'main': Demo().mainloop()
462 | Chapter 8: A tkinter Tour, Part 1