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

(yzsuai) #1

Python tkinter GUIs and provide an even more professional look and feel. To hint at
what is to come, let’s put tkinter to work on our database of people.


A GUI Shelve Interface


For our database application, the first thing we probably want is a GUI for viewing the
stored data—a form with field names and values—and a way to fetch records by key.
It would also be useful to be able to update a record with new field values given its key
and to add new records from scratch by filling out the form. To keep this simple, we’ll
use a single GUI for all of these tasks. Figure 1-7 shows the window we are going to
code as it looks in Windows 7; the record for the key sue has been fetched and displayed
(our shelve is as we last left it again). This record is really an instance of our class in our
shelve file, but the user doesn’t need to care.


Figure 1-7. peoplegui.py main display/input window


Coding the GUI


Also, to keep this simple, we’ll assume that all records in the database have the same
sets of fields. It would be a minor extension to generalize this for any set of fields (and
come up with a general form GUI constructor tool in the process), but we’ll defer such
evolutions to later in this book. Example 1-29 implements the GUI shown in Figure 1-7.


Example 1-29. PP4E\Preview\peoplegui.py


"""
Implement a GUI for viewing and updating class instances stored in a shelve;
the shelve lives on the machine this script runs on, as 1 or more local files;
"""


from tkinter import *
from tkinter.messagebox import showerror
import shelve
shelvename = 'class-shelve'
fieldnames = ('name', 'age', 'job', 'pay')


46 | Chapter 1: A Sneak Preview

Free download pdf