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

(yzsuai) #1

on buttons instead of text), but part of the power of tkinter is that we need to set only
the options we are interested in tailoring.


Using OOP for GUIs


All of our GUI examples so far have been top-level script code with a function for
handling events. In larger programs, it is often more useful to code a GUI as a subclass
of the tkinter Frame widget—a container for other widgets. Example 1-25 shows our
single-button GUI recoded in this way as a class.


Example 1-25. PP4E\Preview\tkinter102.py


from tkinter import *
from tkinter.messagebox import showinfo


class MyGui(Frame):
def init(self, parent=None):
Frame.init(self, parent)
button = Button(self, text='press', command=self.reply)
button.pack()
def reply(self):
showinfo(title='popup', message='Button pressed!')


if name == 'main':
window = MyGui()
window.pack()
window.mainloop()


The button’s event handler is a bound method—self.reply, an object that remembers
both self and reply when later called. This example generates the same window and
pop up as Example 1-24 (Figures 1-2 and 1-3); but because it is now a subclass of
Frame, it automatically becomes an attachable component—i.e., we can add all of the
widgets this class creates, as a package, to any other GUI, just by attaching this Frame
to the GUI. Example 1-26 shows how.


Figure 1-3. tkinter101.py common dialog pop up


42 | Chapter 1: A Sneak Preview

Free download pdf