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

(yzsuai) #1

open’s encoding on saves, and even internal program values (parsed from email head-
ers, for instance). These sources are attempted until the first that succeeds, though it
may also be desirable to limit encoding attempts to just one such source in some
contexts.


Watch for this code in Chapter 14. Frankly, PyEdit in this edition originally read and
wrote files in text mode with platform default encodings. I didn’t consider the impli-
cations of Unicode on PyEdit until the PyMailGUI example’s Internet world raised the
specter of arbitrary text encodings. If it seems that strings are a lot more complicated
than they used to be, it’s probably only because your scope has been too narrow.


Advanced Text and Tag Operations


But enough about the idiosyncrasies of Unicode text—let’s get back to coding GUIs.
Besides the position specification roles we’ve seen so far, the Text widget’s text tags can
also be used to apply formatting and behavior to all characters in a substring and all
substrings added to a tag. In fact, this is where much of the power of the Text widget lies:



  • Tags have formatting attributes for setting color, font, tabs, and line spacing and
    justification; to apply these to many parts of the text at once, associate them with
    a tag and apply formatting to the tag with the tag_config method, much like the
    general config widget we’ve been using.

  • Tags can also have associated event bindings, which let you implement things such
    as hyperlinks in a Text widget: clicking the text triggers its tag’s event handler. Tag
    bindings are set with a tag_bind method, much like the general widget bind method
    we’ve already met.


With tags, it’s possible to display multiple configurations within the same Text widget;
for instance, you can apply one font to the Text widget at large and other fonts to tagged
text. In addition, the Text widget allows you to embed other widgets at an index (they
are treated like a single character), as well as images.


Example 9-12 illustrates the basics of all these advanced tools at once and draws the
interface captured in Figure 9-22. This script applies formatting and event bindings to
three tagged substrings, displays text in two different font and color schemes, and em-
beds an image and a button. Double-clicking any of the tagged substrings (or the em-
bedded button) with a mouse triggers an event that prints a “Got tag event” message
to stdout.


Example 9-12. PP4E\Gui\Tour\texttags.py


"demo advanced tag and text interfaces"


from tkinter import *
root = Tk()
def hello(event): print('Got tag event')


make and config a Text


548 | Chapter 9: A tkinter Tour, Part 2

Free download pdf