Creating and Using a Text Widget
Text Widget Options
A Short Break for a Simple Example
Text Indexes
Text Tags
Inserting Text
Deleting Text
Retrieving Text
Translating Index Values
Comparing Index Values
Showing an Index
Getting the Size of a Character
Getting Line Information
Searching the Contents of a Text Widget
Scrolling
Marks
Embedding Widgets
Internal Debug Flag
The Perl/Tk Text Widget Extended Methods
The TextUndo Widget
The ROText Widget
The Text widget is one of the most powerful standard widgets available in Perl/Tk. It is flexible, configurable, and easy to use for simple tasks. You can use Text widgets to:
Display and edit a plain text file
Display formatted text from an HTML document
Create a scrollable color key, with Buttons that allow you change the colors
Gather multiline, formatted text (including colors) from a user (act as a mini word processor)
Display text with different colors based on the input
Create hypertext windows that perform actions when clicked (either HTML or similar to the widget demo).[16]
[16] When you installed the Tk module with Perl, you also installed the widget demo. Type widget on the command line to see the capabilities of widgets in Perl/Tk.
You can put text as well as other widgets inside a Text widget. A Text widget can be used in conjunction with Scrollbars to allow many pages of information to be viewed in much less space.
To create a Text widget, use the Text method from the desired parent widget:
$text = $parent->Text( [ options ... ] )->pack;
After the Text widget is created, there are several different ways to place text in it. The user can type directly into it, or you can use the insert method:
$text->insert('end', "To be or not to be...\nThat is the question");
The basic form of the insert method takes two arguments: an index value that indicates where to start placing the text, followed by the string to insert. For complete details on the insert method and how to insert multiple strings at the same time, see Section 8.6, "Inserting Text" later in this chapter.
A typical use of the Text widget is to read a file and place it in the Text widget as it's read:
$text = $mw->Scrolled("Text")->pack( ); open (FH, "chapter1") || die "Could not open chapter1"; while (<FH>) { $text->insert('end', $_); } close(FH);
You can use the Text widget to display the file backward (line by line) by changing the insert line to $text->insert(0, $_). This will put the next line read at the top of the Text widget instead of at the end.
The Text widget can do a lot more than just display a file or two lines from a Shakespearean play. In addition to options, we also have tags, indexes, and marks to control how the contents of a Text widget are displayed.