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

(yzsuai) #1
self.text.tag_add('alltext', '1.0', END) # tag all text in the widget
self.text.tag_add(SEL, index1, index2) # select from index1 up to index2
self.text.tag_remove(SEL, '1.0', END) # remove selection from all text

The first line here creates a new tag that names all text in the widget—from start through
end positions. The second line adds a range of characters to the built-in SEL selection
tag—they are automatically highlighted, because this tag is predefined to configure its
members that way. The third line removes all characters in the text string from the
SEL tag (all selections are unselected). Note that the tag_remove call just untags text
within the named range; to really delete a tag completely, call tag_delete instead. Also
keep in mind that these calls apply to tags themselves; to delete actual text use the
delete method shown earlier.


You can map indexes to tags dynamically, too. For example, the text search method
returns the row.column index of the first occurrence of a string between start and stop
positions. To automatically select the text thus found, simply add its index to the built-
in SEL tag:


where = self.text.search(target, INSERT, END) # search from insert cursor
pastit = where + ('+%dc' % len(target)) # index beyond string found
self.text.tag_add(SEL, where, pastit) # tag and select found string
self.text.focus() # select text widget itself

If you want only one string to be selected, be sure to first run the tag_remove call listed
earlier—this code adds a selection in addition to any selections that already exist (it
may generate multiple selections in the display). In general, you can add any number
of substrings to a tag to process them as a group.


To summarize: indexes, marks, and tag locations can be used anytime you need a text
position. For instance, the text see method scrolls the display to make a position visible;
it accepts all three kinds of position specifiers:


self.text.see('1.0') # scroll display to top
self.text.see(INSERT) # scroll display to insert cursor mark
self.text.see(SEL_FIRST) # scroll display to selection tag

Text tags can also be used in broader ways for formatting and event bindings, but I’ll
defer those details until the end of this section.


Adding Text-Editing Operations


Example 9-11 puts some of these concepts to work. It extends Example 9-10 to add
support for four common text-editing operations—file save, text cut and paste, and
string find searching—by subclassing ScrolledText to provide additional buttons and
methods. The Text widget comes with a set of default keyboard bindings that perform
some common editing operations, too, but they might not be what is expected on every
platform; it’s more common and user friendly to provide GUI interfaces to editing
operations in a GUI text editor.


Text | 533
Free download pdf