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

(yzsuai) #1

We’ll meet such a text editor component in Chapter 11. For now, Example 7-20 illus-
trates the concept in a simple way. The script gui6.py produces the window in
Figure 7-20.


Example 7-20. PP4E\Gui\Intro\gui6.py


from tkinter import *


class Hello(Frame): # an extended Frame
def init(self, parent=None):
Frame.init(self, parent) # do superclass init
self.pack()
self.data = 42
self.make_widgets() # attach widgets to self


def make_widgets(self):
widget = Button(self, text='Hello frame world!', command=self.message)
widget.pack(side=LEFT)


def message(self):
self.data += 1
print('Hello frame world %s!' % self.data)


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


Figure 7-20. A custom Frame in action


This example pops up a single-button window. When pressed, the button triggers the
self.message bound method to print to stdout again. Here is the output after pressing
this button four times; notice how self.data (a simple counter here) retains its state
between presses:


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

This may seem like a roundabout way to show a Button (we did it in fewer lines in
Examples 7-10, 7-11, and 7-12). But the Hello class provides an enclosing organiza-
tional structure for building GUIs. In the examples prior to the last section, we made
GUIs using a function-like approach: we called widget constructors as though they
were functions and hooked widgets together manually by passing in parents to widget
construction calls. There was no notion of an enclosing context, apart from the global


404 | Chapter 7: Graphical User Interfaces

Free download pdf