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

(yzsuai) #1

Button(frm, text='State', command=self.report).pack(fill=X)
Quitter(frm).pack(fill=X)


if name == 'main': Demo().mainloop()


In terms of program code, check buttons resemble normal buttons; they are even
packed within a container widget. Operationally, though, they are a bit different. As
you can probably tell from this figure (and can better tell by running this live), a check
button works as a toggle—pressing one changes its state from off to on (from deselected
to selected); or from on to off again. When a check button is selected, it has a checked
display, and its associated IntVar variable has a value of 1 ; when deselected, its display
is empty and its IntVar has a value of 0.


To simulate an enclosing application, the State button in this display triggers the script’s
report method to display the current values of all five toggles on the stdout stream.
Here is the output after a few clicks:


C:\...\PP4E\Gui\Tour> python demoCheck.py
0 0 0 0 0
1 0 0 0 0
1 0 1 0 0
1 0 1 1 0
1 0 0 1 0
1 0 0 1 1

Really, these are the values of the five tkinter variables associated with the
Checkbuttons with variable options, but they give the buttons’ values when queried.
This script associates IntVar variables with each Checkbutton in this display, since they
are 0 or 1 binary indicators. StringVars will work here, too, although their get methods
would return strings '0' or '1' (not integers) and their initial state would be an empty
string (not the integer 0).


This widget’s command option lets you register a callback to be run each time the button
is pressed. To illustrate, this script registers a standard dialog demo call as a handler
for each of the Checkbuttons—pressing a button changes the toggle’s state but also pops
up one of the dialog windows we visited earlier in this tour (regardless of its new state).


Interestingly, you can sometimes run the report method interactively, too—when
working as follows in a shell window, widgets pop up as lines are typed and are fully
active, even without calling mainloop (though this may not work in some interfaces like
IDLE if you must call mainloop to display your GUI):


C:\...\PP4E\Gui\Tour> python
>>> from demoCheck import Demo
>>> d = Demo()
>>> d.report()
0 0 0 0 0
>>> d.report()
1 0 0 0 0
>>> d.report()
1 0 0 1 1

Checkbutton, Radiobutton, and Scale | 459
Free download pdf