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

(yzsuai) #1
Both kinds of buttons provide both command a n d variable o p t i o n s. T h e command option
lets you register a callback to be run immediately on button-press events, much like
normal Button widgets. But by associating a tkinter variable with the variable option,
you can also fetch or change widget state at any time by fetching or changing the value
of the widget’s associated variable.
Since it’s a bit simpler, let’s start with the tkinter Checkbutton. Example 8-22 creates
the set of five captured in Figure 8-26. To make this more useful, it also adds a button
that dumps the current state of all Checkbuttons and attaches an instance of the verifying
Quitter button we built earlier in the tour.

Figure 8-26. demoCheck in action

Example 8-22. PP4E\Gui\Tour\demoCheck.py
"create a bar of check buttons that run dialog demos"

from tkinter import * # get base widget set
from dialogTable import demos # get canned dialogs
from quitter import Quitter # attach a quitter object to "me"

class Demo(Frame):
def __init__(self, parent=None, **options):
Frame.__init__(self, parent, **options)
self.pack()
self.tools()
Label(self, text="Check demos").pack()
self.vars = []
for key in demos:
var = IntVar()
Checkbutton(self,
text=key,
variable=var,
command=demos[key]).pack(side=LEFT)
self.vars.append(var)

def report(self):
for var in self.vars:
print(var.get(), end=' ') # current toggle settings: 1 or 0
print()

def tools(self):
frm = Frame(self)
frm.pack(side=RIGHT)

458 | Chapter 8: A tkinter Tour, Part 1

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf