This should come up with button “5” selected initially, but it doesn’t. The variable
referenced by local tmp is reclaimed on function exit, the Tk variable is unset, and the 5
setting is lost (all buttons come up unselected). These radio buttons work fine, though,
once you start pressing them, because that resets the internal Tk variable. Uncomment-
ing the global statement here makes 5 start out set, as expected.
This phenomenon seems to have grown even worse in Python 3.X: not only is “5” not
selected initially, but moving the mouse cursor over the unselected buttons seems to
select many at random until one is pressed. (In 3.X we also need to initialize a String
Var shared by radio buttons as we did in this section’s earlier examples, or else its empty
string default selects all of them!)
Of course, this is an atypical example—as coded, there is no way to know which button
is pressed, because the variable isn’t saved (and command isn’t set). It makes little sense
to use a group of radio buttons at all if you cannot query its value later. In fact, this is
so obscure that I’ll just refer you to demo-radio-clear2.py in the book’s examples dis-
tribution for an example that works hard to trigger this oddity in other ways. You
probably won’t care, but you can’t say that I didn’t warn you if you ever do.
Scales (Sliders)
Scales (sometimes called “sliders”) are used to select among a range of numeric values.
Moving the scale’s position with mouse drags or clicks moves the widget’s value among
a range of integers and triggers Python callbacks if registered.
Like check buttons and radio buttons, scales have both a command option for registering
an event-driven callback handler to be run right away when the scale is moved, and a
variable option for associating a tkinter variable that allows the scale’s position to be
fetched and set at arbitrary times. You can process scale settings when they are made,
or let the user pick a setting for later use.
In addition, scales have a third processing option—get and set methods that scripts
may call to access scale values directly without associating variables. Because scale
command movement callbacks also get the current scale setting value as an argument, it’s
often enough just to provide a callback for this widget, without resorting to either linked
variables or get/set method calls.
To illustrate the basics, Example 8-30 makes two scales—one horizontal and one ver-
tical—and links them with an associated variable to keep them in sync.
Example 8-30. PP4E\Gui\Tour\demoScale.py
"create two linked scales used to launch dialog demos"
from tkinter import * # get base widget set
from dialogTable import demos # button callback handlers
from quitter import Quitter # attach a quit frame to me
Checkbutton, Radiobutton, and Scale | 467