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

(yzsuai) #1

Notice how the end of this script opens the shelve as a global variable and starts the
GUI; the shelve remains open for the lifespan of the GUI (mainloop returns only after
the main window is closed). As we’ll see in the next section, this state retention is very
different from the web model, where each interaction is normally a standalone program.
Also notice that the use of global variables makes this code simple but unusable outside
the context of our database; more on this later.


Using the GUI


The GUI we’re building is fairly basic, but it provides a view on the shelve file and
allows us to browse and update the file without typing any code. To fetch a record from
the shelve and display it on the GUI, type its key into the GUI’s “key” field and click
Fetch. To change a record, type into its input fields after fetching it and click Update;
the values in the GUI will be written to the record in the database. And to add a new
record, fill out all of the GUI’s fields with new values and click Update—the new record
will be added to the shelve file using the key and field inputs you provide.


In other words, the GUI’s fields are used for both display and input. Figure 1-8 shows
the scene after adding a new record (via Update), and Figure 1-9 shows an error dialog
pop up issued when users try to fetch a key that isn’t present in the shelve.


Figure 1-8. peoplegui.py after adding a new persistent object


Figure 1-9. peoplegui.py common error dialog pop up


48 | Chapter 1: A Sneak Preview

Free download pdf