When run with arguments, the script stores a file’s contents in the Text widget. When
run without arguments, the script stuffs a simple literal string into the widget, displayed
by the first Escape press output here (recall that \n is the escape sequence for the line-
end character). The second output here happens after editing the window’s text, when
pressing Escape in the shrunken window captured in Figure 9-18. By default, Text
widget text is fully editable using the usual edit operations for your platform.
Figure 9-18. scrolledtext gets a positive outlook
String positions
The second key to understanding Text code has to do with the ways you specify a
position in the text string. Like the listbox, Text widgets allow you to specify such a
position in a variety of ways. In Text, methods that expect a position to be passed in
will accept an index, a mark, or a tag reference. Moreover, some special operations are
invoked with predefined marks and tags—the insert cursor is mark INSERT, and the
current selection is tag SEL. Since they are fundamental to Text and the source of much
of its expressive power, let’s take a closer look at these settings.
Because it is a multiple-line widget, Text indexes identify both a line and a
column. For instance, consider the interfaces of the basic insert, delete, and fetch text
operations used by this script:
self.text.insert('1.0', text) # insert text at the start
self.text.delete('1.0', END) # delete all current text
return self.text.get('1.0', END+'-1c') # fetch first through last
In all of these, the first argument is an absolute index that refers to the start of the text
string: string '1.0' means row 1, column 0 (rows are numbered from 1 and columns
from 0, though '0.0' is accepted as a reference to the start of the text, too). An index
'2.1' refers to the second character in the second row.
Like the listbox, text indexes can also be symbolic names: the END in the preceding
delete call refers to the position just past the last character in the text string (it’s a
tkinter variable preset to string 'end'). Similarly, the symbolic index INSERT (really,
string 'insert') refers to the position immediately after the insert cursor—the place
where characters would appear if typed at the keyboard. Symbolic names such as
INSERT can also be called marks, described in a moment.
Text indexes.
Text | 531