Example 8-28. PP4E\Gui\Tour\demo-radio-auto.py
radio buttons, the easy way
from tkinter import *
root = Tk() # IntVars work too
var = IntVar(0) # select 0 to start
for i in range(10):
rad = Radiobutton(root, text=str(i), value=i, variable=var)
rad.pack(side=LEFT)
root.mainloop()
print(var.get()) # show state on exit
This works the same way, but it is a lot less to type and debug. Notice that this script
associates the buttons with an IntVar, the integer type sibling of StringVar, and initi-
alizes it to zero (which is also its default); as long as button values are unique, integers
work fine for radio buttons too.
Hold onto your variables!
One minor word of caution: you should generally hold onto the tkinter variable object
used to link radio buttons for as long as the radio buttons are displayed. Assign it to a
module global variable, store it in a long-lived data structure, or save it as an attribute
of a long-lived class instance object as done by demoRadio. Just make sure you retain a
reference to it somehow. You normally will in order to fetch its state anyhow, so it’s
unlikely that you’ll ever care about what I’m about to tell you.
But in the current tkinter, variable classes have a del destructor that automatically
unsets a generated Tk variable when the Python object is reclaimed (i.e., garbage col-
lected). The upshot is that all of your radio buttons may be deselected if the variable
object is collected, at least until the next press resets the Tk variable to a new value.
Example 8-29 shows one way to trigger this.
Example 8-29. PP4E\Gui\Tour\demo-radio-clear.py
hold on to your radio variables (an obscure thing, indeed)
from tkinter import *
root = Tk()
def radio1(): # local vars are temporary
#global tmp # making it global fixes the problem
tmp = IntVar()
for i in range(10):
rad = Radiobutton(root, text=str(i), value=i, variable=tmp)
rad.pack(side=LEFT)
tmp.set(5) # select 6th button
radio1()
root.mainloop()
466 | Chapter 8: A tkinter Tour, Part 1