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

(yzsuai) #1
for i in range(250):
f.write('%03d) All work and no play makes Jack a dull boy.\n' % i)
f.close()

C:\...\PP4E\Gui\Tour> python makefile.py

C:\...\PP4E\Gui\Tour> python scrolledtext.py jack.txt
PP4E scrolledtext

To view a file, pass its name on the command line—its text is automatically displayed
in the new window. By default, it is shown in a font that may vary per platform (and
might not be fixed-width on some), but we’ll pass a font option to the Text widget in
the next example to change that. Pressing the Escape key fetches and displays the full
text content of the widget as a single string (more on this in a moment).


Notice the PP4E scrolledtext message printed when this script runs. Because there is
also a scrolledtext.py file in the standard Python distribution (in module
tkinter.scrolledtext) with a very different implementation and interface, the one here
identifies itself when run or imported, so you can tell which one you’ve got. If the
standard library’s alternative ever goes away, import the class listed to get a simple text
browser, and adjust any text widget configuration calls to include a .text qualifier level
(e.g., x.text.config instead of x.config; the library version subclasses Text directly,
not Frame).


Programming the Text Widget


To understand how this script works at all, though, we have to detour into a few
Text widget details here. Earlier we met the Entry and Message widgets, which address
a subset of the Text widget’s uses. The Text widget is much richer in both features and
interfaces—it supports both input and display of multiple lines of text, editing opera-
tions for both programs and interactive users, multiple fonts and colors, and much
more. Text objects are created, configured, and packed just like any other widget, but
they have properties all their own.


Text is a Python string


Although the Text widget is a powerful tool, its interface seems to boil down to two
core concepts. First, the content of a Text widget is represented as a string in Python
scripts, and multiple lines are separated with the normal \n line terminator. The string
'Words\ngo here', for instance, represents two lines when stored in or fetched from a
Text widget; it would normally have a trailing \n also, but it doesn’t have to.


To help illustrate this point, this script binds the Escape key press to fetch and print
the entire contents of the Text widget it embeds:


C:\...\PP4E\Gui\Tour> python scrolledtext.py
PP4E scrolledtext
'Words\ngo here'
'Always look\non the bright\nside of life\n'

530 | Chapter 9: A tkinter Tour, Part 2

Free download pdf