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

(yzsuai) #1

If you press 1, 4, or 7 now, all three of these are selected, and any existing selections
are cleared (they don’t have the value “1”). That’s not normally what you want—radio
buttons are usually a single-choice group (check buttons handle multiple-choice in-
puts). If you want them to work as expected, be sure to give each radio button the same
variable but a unique value across the entire group. In the demoRadio script, for instance,
the name of the demo provides a naturally unique value for each button.


Radio buttons without variables


Strictly speaking, we could get by without tkinter variables here, too. Example 8-27,
for instance, implements a single-selection model without variables, by manually se-
lecting and deselecting widgets in the group, in a callback handler of its own. On each
press event, it issues deselect calls for every widget object in the group and select for
the one pressed.


Example 8-27. PP4E\Gui\Tour\demo-radio-manual.py


"""
radio buttons, the hard way (without variables)
note that deselect for radio buttons simply sets the button's
associated value to a null string, so we either need to still
give buttons unique values, or use checkbuttons here instead;
"""


from tkinter import *
state = ''
buttons = []


def onPress(i):
global state
state = i
for btn in buttons:
btn.deselect()
buttons[i].select()


root = Tk()
for i in range(10):
rad = Radiobutton(root, text=str(i),
value=str(i), command=(lambda i=i: onPress(i)) )
rad.pack(side=LEFT)
buttons.append(rad)


onPress(0) # select first initially
root.mainloop()
print(state) # show state on exit


This works. It creates a 10-radio button window that looks just like the one in Fig-
ure 8-29 but implements a single-choice radio-style interface, with current state avail-
able in a global Python variable printed on script exit. By associating tkinter variables
and unique values, though, you can let tkinter do all this work for you, as shown in
Example 8-28.


Checkbutton, Radiobutton, and Scale | 465
Free download pdf