[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

fact, to make radio buttons work normally at all, it’s crucial that they are all associated
with the same tkinter variable and have distinct value settings. To truly understand
why, though, you need to know a bit more about how radio buttons and variables do
their stuff.


We’ve already seen that changing a widget changes its associated tkinter variable, and
vice versa. But it’s also true that changing a variable in any way automatically changes
every widget it is associated with. In the world of radio buttons, pressing a button sets
a shared variable, which in turn impacts other buttons associated with that variable.
Assuming that all radio buttons have distinct values, this works as you expect it to
work. When a button press changes the shared variable to the pressed button’s value,
all other buttons are deselected, simply because the variable has been changed to a
value not their own.


This is true both when the user selects a button and changes the shared variable’s value
implicitly, but also when the variable’s value is set manually by a script. For instance,
when Example 8-25 sets the shared variable to the last of the demo’s names initially
(with self.var.set), it selects that demo’s button and deselects all the others in the
process; this way, only one is selected at first. If the variable was instead set to a string
that is not any demo’s name (e.g., ' '), all buttons would be deselected at startup.


This ripple effect is a bit subtle, but it might help to know that within a group of radio
buttons sharing the same variable, if you assign a set of buttons the same value, the
entire set will be selected if any one of them is pressed. Consider Example 8-26, which
creates Figure 8-29, for instance. All buttons start out deselected this time (by initial-
izing the shared variable to none of their values), but because radio buttons 0, 3, 6, and
9 have value 0 (the remainder of division by 3), all are selected if any are selected.


Figure 8-29. Radio buttons gone bad?


Example 8-26. PP4E\Gui\Tour\demo-radio-multi.py


see what happens when some buttons have same value


from tkinter import *
root = Tk()
var = StringVar()
for i in range(10):
rad = Radiobutton(root, text=str(i), variable=var, value=str(i % 3))
rad.pack(side=LEFT)
var.set(' ') # deselect all initially
root.mainloop()


464 | Chapter 8: A tkinter Tour, Part 1

Free download pdf