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

(yzsuai) #1

Figure 8-22. entry1 caught in the act


On startup, the entry1 script fills the input field in this GUI with the text “Type words
here” by calling the widget’s insert method. Because both the Fetch button and the
Enter key are set to trigger the script’s fetch callback function, either user event gets
and displays the current text in the input field, using the widget’s get method:


C:\...\PP4E\Gui\Tour> python entry1.py
Input => "Type words here"
Input => "Have a cigar"

We met the event earlier when we studied bind; unlike button presses, these
lower-level callbacks get an event argument, so the script uses a lambda wrapper to
ignore it. This script also packs the entry field with fill=X to make it expand horizon-
tally with the window (try it out), and it calls the widget focus method to give the entry
field input focus when the window first appears. Manually setting the focus like this
saves the user from having to click the input field before typing. Our smart Quit button
we wrote earlier is attached here again as well (it verifies exit).


Programming Entry widgets


Generally speaking, the values typed into and displayed by Entry widgets are set and
fetched with either tied “variable” objects (described later in this chapter) or Entry
widget method calls such as this one:


ent.insert(0, 'some text') # set value
value = ent.get() # fetch value (a string)

The first parameter to the insert method gives the position where the text is to be
inserted. Here, “0” means the front because offsets start at zero, and integer 0 and string
'0' mean the same thing (tkinter method arguments are always converted to strings if
needed). If the Entry widget might already contain text, you also generally need to delete
its contents before setting it to a new value, or else new text will simply be added to
the text already present:


ent.delete(0, END) # first, delete from start to end
ent.insert(0, 'some text') # then set value

The name END here is a preassigned tkinter constant denoting the end of the widget;
we’ll revisit it in Chapter 9 when we meet the full-blown and multiple-line Text widget
(Entry’s more powerful cousin). Since the widget is empty after the deletion, this state-
ment sequence is equivalent to the prior one:


450 | Chapter 8: A tkinter Tour, Part 1

Free download pdf