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

(yzsuai) #1
ent.delete('0', END) # delete from start to end
ent.insert(END, 'some text') # add at end of empty text

Either way, if you don’t delete the text first, new text that is inserted is simply added.
If you want to see how, try changing the fetch function in Example 8-17 to look like
this—an “x” is added at the beginning and end of the input field on each button or key
press:


def fetch():
print('Input => "%s"' % ent.get()) # get text
ent.insert(END, 'x') # to clear: ent.delete('0', END)
ent.insert(0, 'x') # new text simply added

In later examples, we’ll also see the Entry widget’s state='disabled' option, which
makes it read only, as well as its show='' option, which makes it display each character
as a
(useful for password-type inputs). Try this out on your own by changing and
running this script for a quick look. Entry supports other options we’ll skip here, too;
see later examples and other resources for additional details.


Laying Out Input Forms


As mentioned, Entry widgets are often used to get field values in form-like displays.
We’re going to create such displays often in this book, but to show you how this works
in simpler terms, Example 8-18 combines labels, entries, and frames to achieve the
multiple-input display captured in Figure 8-23.


Example 8-18. PP4E\Gui\Tour\entry2.py


"""
use Entry widgets directly
lay out by rows with fixed-width labels: this and grid are best for forms
"""


from tkinter import *
from quitter import Quitter
fields = 'Name', 'Job', 'Pay'


def fetch(entries):
for entry in entries:
print('Input => "%s"' % entry.get()) # get text


def makeform(root, fields):
entries = []
for field in fields:
row = Frame(root) # make a new row
lab = Label(row, width=5, text=field) # add label, entry
ent = Entry(row)
row.pack(side=TOP, fill=X) # pack row on top
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X) # grow horizontal
entries.append(ent)
return entries


Message and Entry | 451
Free download pdf