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

(yzsuai) #1

You can launch this example in IDLE, from a console command line, or by clicking its
icon—the same way you can run other Python scripts. tkinter itself is a standard part
of Python and works out-of-the-box on Windows and others, though you may need
extra configuration or install steps on some computers (more details later in this book).


It’s not much more work to code a GUI that actually responds to a user: Exam-
ple 1-24 implements a GUI with a button that runs the reply function each time it is
pressed.


Example 1-24. PP4E\Preview\ tkinter101.py


from tkinter import *
from tkinter.messagebox import showinfo


def reply():
showinfo(title='popup', message='Button pressed!')


window = Tk()
button = Button(window, text='press', command=reply)
button.pack()
window.mainloop()


This example still isn’t very sophisticated—it creates an explicit Tk main window for
the application to serve as the parent container of the button, and it builds the simple
window shown in Figure 1-2 (in tkinter, containers are passed in as the first argument
when making a new widget; they default to the main window). But this time, each time
you click the “press” button, the program responds by running Python code that pops
up the dialog window in Figure 1-3.


Figure 1-2. tkinter101.py main window


Notice that the pop-up dialog looks like it should for Windows 7, the platform on
which this screenshot was taken; again, tkinter gives us a native look and feel that is
appropriate for the machine on which it is running. We can customize this GUI in many
ways (e.g., by changing colors and fonts, setting window titles and icons, using photos


Figure 1-1. tkinter001.py window


Step 5: Adding a GUI | 41
Free download pdf