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

(yzsuai) #1

part.pack(side=RIGHT) # FAILS!--need part.top.pack(side=RIGHT)
frm.mainloop()


This won’t quite work, because part isn’t really a widget. To treat it as such, you must
descend to part.top before making GUI configurations and hope that the name top is
never changed by the class’s developer. In other words, it exposes some of the class’s
internals. The class could make this better by defining a method that always routes
unknown attribute fetches to the embedded Frame, as in Example 7-26.


Example 7-26. PP4E\Gui\Intro\gui7c.py


import gui7
from tkinter import *


class HelloPackage(gui7.HelloPackage):
def getattr(self, name):
return getattr(self.top, name) # pass off to a real widget


if name == 'main': HelloPackage().mainloop() # invokes getattr!


As is, this script simply creates Figure 7-23 again; changing Example 7-25 to import
this extended HelloPackage from gui7c, though, produces the correctly-working win-
dow in Figure 7-24.


Figure 7-24. A standalone class package in action


Routing attribute fetches to nested widgets works this way, but that then requires even
more extra coding in standalone package classes. As usual, though, the significance of
all these trade-offs varies per application.


The End of the Tutorial


In this chapter, we learned the core concepts of Python/tkinter programming and met
a handful of simple widget objects along the way—e.g., labels, buttons, frames, and
the packer geometry manager. We’ve seen enough to construct simple interfaces, but
we have really only scratched the surface of the tkinter widget set.


In the next two chapters, we will apply what we’ve learned here to study the rest of the
tkinter library, and we’ll learn how to use it to generate the kinds of interfaces you
expect to see in realistic GUI programs. As a preview and roadmap, Table 7-1 lists the
kinds of widgets we’ll meet there in roughly their order of appearance. Note that this


410 | Chapter 7: Graphical User Interfaces

Free download pdf