Text Indexes

When we talked about Listbox index values, each index referred to a line in the Listbox. The first line in the Listbox was at index 0, and so on. With a Text widget, the index can point to a specific line, but it can also point to a character within that line. An index for a Text widget is built using a base index and then optionally modifying that index. The entire index, base, and modifier should be put in double quotes.

Base Index Values

Here is a list of base index values:

' n.m '

This format allows you to explicitly specify a line number and a character number within that line. Lines start at 1 (which is different than the Listbox widget), and characters start at 0.

'@x,y'

The character in the widget that is closest to the (x, y) coordinate.

'end'

The very end of the Text widget, after any "\n" characters as well.

' mark '

This specifies the character after the location named mark. The two mark names provided by Tk are "current" and "insert". We’ll discuss what they refer to later in this chapter.

' tag . first'

A tag name is simply a placeholder for some special formatting instructions (discussed in the very next section). After creating tags, you can use this index form. tag . first is the first character in the Text widget that is of type tag. That is, you could create a "heading" tag and use a "heading.first" index.

' tag . last'

This specifies the character directly after the text marked with tag.

$widget

If you have an embedded widget, you can refer ...

Get Mastering Perl/Tk now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.