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

(yzsuai) #1

class CustomGui(MyGui): # inherit init
def reply(self): # replace reply
showinfo(title='popup', message='Ouch!')


if name == 'main':
CustomGui().pack()
mainloop()


When run, this script creates the same main window and button as the original MyGui
class. But pressing its button generates a different reply, as shown in Figure 1-5, because
the custom version of the reply method runs.


Figure 1-5. Customizing GUIs


Although these are still small GUIs, they illustrate some fairly large ideas. As we’ll see
later in the book, using OOP like this for inheritance and attachment allows us to reuse
packages of widgets in other programs—calculators, text editors, and the like can be
customized and added as components to other GUIs easily if they are classes. As we’ll
also find, subclasses of widget class can provide a common appearance or standardized
behavior for all their instances—similar in spirit to what some observers might call GUI
styles or themes. It’s a normal byproduct of Python and OOP.


Getting Input from a User


As a final introductory script, Example 1-28 shows how to input data from the user in
an Entry widget and display it in a pop-up dialog. The lambda it uses defers the call to
the reply function so that inputs can be passed in—a common tkinter coding pattern;
without the lambda, reply would be called when the button is made, instead of when
it is later pressed (we could also use ent as a global variable within reply, but that makes
it less general). This example also demonstrates how to change the icon and title of a
top-level window; here, the window icon file is located in the same directory as the
script (if the icon call in this script fails on your platform, try commenting-out the call;
icons are notoriously platform specific).


44 | Chapter 1: A Sneak Preview

Free download pdf