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

(yzsuai) #1
h
a
m
::::::::::::::::::::textpak=>spam.txt
spam
Spam
SPAM

These scripts don’t do anything about binary files, compression, or the like, but they
serve to illustrate command-line scripts that require arguments when run. Although
they can be launched with shell commands as above (and hence Python tools like
os.popen and subprocess), their logic is also packaged to be imported and called. For
running them from a GUI, we’ll use the latter direct call interface.


GUI input dialogs


One final piece remains. As is, the packing and unpacking scripts function well as
command-line tools. The callback actions named in Example 10-6’s mytools.py GUI,
though, are expected to do something GUI-oriented. Because the original file packing
and unpacking scripts live in the world of text-based streams and shells, we need to
code wrappers that accept input parameters from more GUI-minded users. In partic-
ular, we need dialogs that prompt for the command-line arguments required.


First, the module in Example 10-9 and its client script in Example 10-10 use the custom
modal dialog techniques we studied in Chapter 8 to pop up an input display to collect
pack script parameters. The code in Example 10-9 was split off to a separate module
because it’s generally useful, In fact, we will reuse it, in both the unpack dialog and
again in PyEdit in Chapter 11.


This is yet another way to automate GUI construction—using it to build a form’s rows
trades 7 or more lines of code per row (6 without a linked variable or browse button)
for just 1. We’ll see another even more automatic form building approach in Chap-
ter 12’s form.py. The utility here, though, is sufficient to shave dozens of lines of code
for nontrivial forms.


Example 10-9. PP4E\Gui\ShellGui\formrows.py


""""
create a label+entry row frame, with optional file open browse button;
this is a separate module because it can save code in other programs too;
caller (or callbacks here): retain returned linked var while row is in use;
"""


from tkinter import * # widgets and presets
from tkinter.filedialog import askopenfilename # file selector dialog


def makeFormRow(parent, label, width=15, browse=True, extend=False):
var = StringVar()
row = Frame(parent)
lab = Label(row, text=label + '?', relief=RIDGE, width=width)
ent = Entry(row, relief=SUNKEN, textvariable=var)


ShellGui: GUIs for Command-Line Tools | 619
Free download pdf