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

(yzsuai) #1

for label in labels:
row = Frame(rows)
row.pack(fill=X)
Label(row, text=label, width=labelsize).pack(side=LEFT)
entry = Entry(row, width=entrysize)
entry.pack(side=RIGHT, expand=YES, fill=X)
self.content[label] = entry
Button(box, text='Cancel', command=self.onCancel).pack(side=RIGHT)
Button(box, text='Submit', command=self.onSubmit).pack(side=RIGHT)
box.master.bind('', (lambda event: self.onSubmit()))


def onSubmit(self): # override this
for key in self.content: # user inputs in
print(key, '\t=>\t', self.content[key].get()) # self.content[k]


def onCancel(self): # override if need
Tk().quit() # default is exit


class DynamicForm(Form):
def init(self, labels=None):
labels = input('Enter field names: ').split()
Form.init(self, labels)
def onSubmit(self):
print('Field values...')
Form.onSubmit(self)
self.onCancel()


if name == 'main':
import sys
if len(sys.argv) == 1:
Form(['Name', 'Age', 'Job']) # precoded fields, stay after submit
else:
DynamicForm() # input fields, go away after submit
mainloop()


Compare the approach of this module with that of the form row builder function we
wrote in Chapter 10’s Example 10-9. While that example much reduced the amount
of code required, the module here is a noticeably more complete and automatic
scheme—it builds the entire form given a set of label names, and provides a dictionary
with every field’s entry widget ready to be fetched.


Running this module standalone triggers its self-test code at the bottom. Without ar-
guments (and when double-clicked in a Windows file explorer), the self-test generates
a form with canned input fields captured in Figure 12-4, and displays the fields’ values
on Enter key presses or Submit button clicks:


C:\...\PP4E\Internet\Sockets> python form.py
Age => 40
Name => Bob
Job => Educator, Entertainer

With a command-line argument, the form class module’s self-test code prompts for an
arbitrary set of field names for the form; fields can be constructed as dynamically as we


A Simple Python File Server | 847
Free download pdf