The Text Widget

Class Text implements a powerful multiline text editor, able to display images and embedded widgets as well as text in one or more fonts and colors. An instance t of Text supports many ways to refer to specific points in t’s contents. t supplies methods and configuration options allowing fine-grained control of operations, content, and rendering. This section covers a large, frequently used subset of this vast functionality. In some very simple cases, you can get by with just three Text-specific idioms:

               t.delete('1.0', END)             # clear the widget's contents
t.insert(END, astring)           # append astring to the widget's contents
somestring = t.get('1.0', END)   # get the widget's contents as a string

END is an index on any Text instance t, indicating the end of t’s text. '1.0' is also an index, indicating the start of t’s text (first line, first column). For more about indices, see Section 16.6.5 later in this chapter.

Text Widget Methods

An instance t of class Text supplies many methods. Methods dealing with marks and tags are covered in later sections. Many methods accept one or two indices into t’s contents. The most frequently used methods are the following.

Giving Text a Scrollbar

You’ll often want to couple a Scrollbar instance to a Text instance in order to let the user scroll through the text. The following example shows how to use a Scrollbar s to control vertical scrolling of a Text instance T:

import Tkinter root = Tkinter.Tk( ) s = Tkinter.Scrollbar(root) T = Tkinter.Text(root) ...

Get Python in a Nutshell 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.