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

(yzsuai) #1

Figure 7-21. An attached class component on the right


This script just adds Hello’s button to the right side of parent—a container Frame. In
fact, the button on the right in this window represents an embedded component: its
button really represents an attached Python class object. Pressing the embedded class’s
button on the right prints a message as before; pressing the new button exits the GUI
by a sys.exit call:


C:\...\PP4E\Gui\Intro> python gui6b.py
Hello frame world 43!
Hello frame world 44!
Hello frame world 45!
Hello frame world 46!

In more complex GUIs, we might instead attach large Frame subclasses to other con-
tainer components and develop each independently. For instance, Example 7-22 is yet
another specialized Frame itself, but it attaches an instance of the original Hello class in
a more object-oriented fashion. When run as a top-level program, it creates a window
identical to the one shown in Figure 7-21.


Example 7-22. PP4E\Gui\Intro\gui6c.py


from tkinter import * # get Tk widget classes
from gui6 import Hello # get the subframe class


class HelloContainer(Frame):
def init(self, parent=None):
Frame.init(self, parent)
self.pack()
self.makeWidgets()


def makeWidgets(self):
Hello(self).pack(side=RIGHT) # attach a Hello to me
Button(self, text='Attach', command=self.quit).pack(side=LEFT)


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


This looks and works exactly like gui6b but registers the added button’s callback han-
dler as self.quit, which is just the standard quit widget method this class inherits from
Frame. The window this time represents two Python classes at work—the embedded
component’s widgets on the right (the original Hello button) and the container’s
widgets on the left.


Naturally, this is a simple example (we attached only a single button here, after all).
But in more practical user interfaces, the set of widget class objects attached in this way


406 | Chapter 7: Graphical User Interfaces

Free download pdf