Next / Previous / Contents

24.8. Methods on Text widgets

These methods are available on all text widgets:

.bbox(index)

Returns the bounding box for the character at the given index, a 4-tuple (x, y, width, height). If the character is not visible, returns None. Note that this method may not return an accurate value unless you call the .update_idletasks() method (see Section 26, “Universal widget methods”).

.compare(index1, op, index2)

Compares the positions of two indices in the text widget, and returns true if the relational op holds between index1 and index2. The op specifies what comparison to use, one of: '<', '<=', '==', '!=', '>=', or '>'.

For example, for a text widget t, t.compare('2.0', '<=', END) returns true if the beginning of the second line is before or at the end of the text in t.

.delete(index1, index2=None)

Deletes text starting just after index1. If the second argument is omitted, only one character is deleted. If a second index is given, deletion proceeds up to, but not including, the character after index2. Recall that indices sit between characters.

.dlineinfo(index)

Returns a bounding box for the line that contains the given index. For the form of the bounding box, and a caution about updating idle tasks, see the definition of the .bbox method above.

.edit_modified(arg=None)

Queries, sets, or clears the modified flag. This flag is used to track whether the contents of the widget have been changed. For example, if you are implementing a text editor in a Text widget, you might use the modified flag to determine whether the contents have changed since you last saved the contents to a file.

When called with no argument, this method returns True if the modified flag has been set, False if it is clear. You can also explicitly set the modified flag by passing a True value to this method, or clear it by passing a False value.

Any operation that inserts or deletes text, whether by program actions or user actions, or an undo or redo operation, will set the modified flag.

.edit_redo()

Performs a redo operation. For details, see Section 24.7, “The Text widget undo/redo stack”.

.edit_reset()

Clears the undo stack.

.edit_separator()

Pushes a separator onto the undo stack. This separator limits the scope of a future undo operation to include only the changes pushed since the separator was pushed. For details, see Section 24.7, “The Text widget undo/redo stack”.

.edit_undo()

Reverses all changes to the widget's contents made since the last separator was pushed on the undo stack, or all the way to the bottom of the stack if the stack contains no separators. For details, see Section 24.7, “The Text widget undo/redo stack”. It is an error if the undo stack is empty.

.image_create(index[, option=value, ...])

This method inserts an image into the widget. The image is treated as just another character, whose size is the image's natural size.

The options for this method are shown in the table below. You may pass either a series of option=value arguments, or a dictionary of option names and values.

align This option specifies how the image is to be aligned vertically if its height is less than the height of its containing line. Values may be top to align it at the top of its space; center to center it; bottom to place it at the bottom; or baseline to line up the bottom of the image with the text baseline.
image The image to be used. See Section 5.9, “Images”.
name You can assign a name to this instance of the image. If you omit this option, Tkinter will generate a unique name. If you create multiple instances of an image in the same Text widget, Tkinter will generate a unique name by appending a “#” followed by a number.
padx If supplied, this option is a number of pixels of extra space to be added on both sides of the image.
pady If supplied, this option is a number of pixels of extra space to be added above and below the image.
.get(index1, index2=None)

Use this method to retrieve the current text from the widget. Retrieval starts at index index1. If the second argument is omitted, you get the character after index1. If you provide a second index, you get the text between those two indices. Embedded images and windows (widgets) are ignored. If the range includes multiple lines, they are separated by newline ('\n') characters.

.image_cget(index, option)

To retrieve the current value of an option set on an embedded image, call this method with an index pointing to the image and the name of the option.

.image_configure(index, option, ...)

To set one or more options on an embedded image, call this method with an index pointing to the image as the first argument, and one or more option=value pairs.

If you specify no options, you will get back a dictionary defining all the options on the image, and the corresponding values.

.image_names()

This method returns a tuple of the names of all the text widget's embedded images.

.index(i)

For an index i, this method returns the equivalent position in the form 'line.char'.

.insert(index, text, tags=None)

Inserts the given text at the given index.

If you omit the tags argument, the newly inserted text will be tagged with any tags that apply to the characters both before and after the insertion point.

If you want to apply one or more tags to the text you are inserting, provide as a third argument a tuple of tag strings. Any tags that apply to existing characters around the insertion point are ignored. Note: The third argument must be a tuple. If you supply a list argument, Tkinter will silently fail to apply the tags. If you supply a string, each character will be treated as a tag.

.mark_gravity(mark, gravity=None)

Changes or queries the gravity of an existing mark; see Section 24.2, “Text widget marks”, above, for an explanation of gravity.

To set the gravity, pass in the name of the mark, followed by either tk.LEFT or tk.RIGHT. To find the gravity of an existing mark, omit the second argument and the method returns tk.LEFT or tk.RIGHT.

.mark_names()

Returns a sequence of the names of all the marks in the window, including tk.INSERT and tk.CURRENT.

.mark_next(index)

Returns the name of the mark following the given index; if there are no following marks, the method returns an empty string.

If the index is in numeric form, the method returns the first mark at that position. If the index is a mark, the method returns the next mark following that mark, which may be at the same numerical position.

.mark_previous(index)

Returns the name of the mark preceding the given index. If there are no preceding marks, the method returns an empty string.

If the index is in numeric form, the method returns returns the last mark at that position. If the index is a mark, the method returns the preceding mark, which may be at the same numerical position.

.mark_set(mark, index)

If no mark with name mark exists, one is created with tk.RIGHT gravity and placed where index points. If the mark already exists, it is moved to the new location.

This method may change the position of the tk.INSERT or tk.CURRENT indices.

.mark_unset(mark)

Removes the named mark. This method cannot be used to remove the tk.INSERT or tk.CURRENT marks.

.scan_dragto(x, y)

See .scan_mark, below.

.scan_mark(x, y)

This method is used to implement fast scrolling of a Text widget. Typically, a user presses and holds a mouse button at some position in the widget, and then moves the mouse in the desired direction, and the widget moves in that direction at a rate proportional to the distance the mouse has moved since the button was depressed. The motion may be any combination of vertical or horizontal scrolling.

To implement this feature, bind a mouse button down event to a handler that calls .scan_mark(x, y), where x and y are the current mouse position. Then bind the <Motion> event to a handler that calls .scan_dragto(x, y), where x and y are the new mouse position.

.search(pattern, index, option, ...)

Searches for pattern (which can be either a string or a regular expression) in the buffer starting at the given index. If it succeeds, it returns an index of the 'line.char' form; if it fails, it returns an empty string.

The allowable options for this method are:

backwards Set this option to True to search backwards from the index. Default is forwards.
count If you set this option to an IntVar control variable, when there is a match you can retrieve the length of the text that matched by using the .get() method on that variable after the method returns.
exact Set this option to True to search for text that exactly matches the pattern. This is the default option. Compare the regexp option below.
forwards Set this option to True to search forwards from the index. This is the default option.
regexp Set this option to True to interpret the pattern as a Tcl-style regular expression. The default is to look for an exact match to pattern. Tcl regular expressions are a subset of Python regular expressions, supporting these features: . ^ [c1…] (…) * + ? e1|e2
nocase Set this option to 1 to ignore case. The default is a case-sensitive search.
stopindex To limit the search, set this option to the index beyond which the search should not go.
.see(index)

If the text containing the given index is not visible, scroll the text until that text is visible.

.tag_add(tagName, index1, index2=None)

This method associates the tag named tagName with a region of the contents starting just after index index1 and extending up to index index2. If you omit index2, only the character after index1 is tagged.

.tag_bind(tagName, sequence, func, add=None)

This method binds an event to all the text tagged with tagName. See Section 54, “Events”, below, for more information on event bindings.

To create a new binding for tagged text, use the first three arguments: sequence identifies the event, and func is the function you want it to call when that event happens.

To add another binding to an existing tag, pass the same first three arguments and '+' as the fourth argument.

To find out what bindings exist for a given sequence on a tag, pass only the first two arguments; the method returns the associated function.

To find all the bindings for a given tag, pass only the first argument; the method returns a list of all the tag's sequence arguments.

.tag_cget(tagName, option)

Use this method to retrieve the value of the given option for the given tagName.

.tag_config(tagName, option, ...)

To change the value of options for the tag named tagName, pass in one or more option=value pairs.

If you pass only one argument, you will get back a dictionary defining all the options and their values currently in force for the named tag.

Here are the options for tag configuration:

background The background color for text with this tag. Note that you can't use bg as an abbreviation.
bgstipple To make the background appear grayish, set this option to one of the standard bitmap names (see Section 5.7, “Bitmaps”). This has no effect unless you also specify a background.
borderwidth Width of the border around text with this tag. Default is 0. Note that you can't use bd as an abbreviation.
fgstipple To make the text appear grayish, set this option a bitmap name.
font The font used to display text with this tag. See Section 5.4, “Type fonts”.
foreground The color used for text with this tag. Note that you can't use the fg abbreviation here.
justify The justify option set on the first character of each line determines how that line is justified: tk.LEFT (the default), tk.CENTER, or tk.RIGHT.
lmargin1 How much to indent the first line of a chunk of text that has this tag. The default is 0. See Section 5.1, “Dimensions”for allowable values.
lmargin2 How much to indent successive lines of a chunk of text that has this tag. The default is 0.
offset How much to raise (positive values) or lower (negative values) text with this tag relative to the baseline. Use this to get superscripts or subscripts, for example. For allowable values, see Section 5.1, “Dimensions”.
overstrike Set overstrike=1 to draw a horizontal line through the center of text with this tag.
relief Which 3-D effect to use for text with this tag. The default is relief=tk.FLAT; for other possible values see Section 5.6, “Relief styles”.
rmargin Size of the right margin for chunks of text with this tag. Default is 0.
spacing1 This option specifies how much extra vertical space is put above each line of text with this tag. If a line wraps, this space is added only before the first line it occupies on the display. Default is 0.
spacing2 This option specifies how much extra vertical space to add between displayed lines of text with this tag when a logical line wraps. Default is 0.
spacing3 This option specifies how much extra vertical space is added below each line of text with this tag. If a line wraps, this space is added only after the last line it occupies on the display. Default is 0.
tabs How tabs are expanded on lines with this tag. See Section 24.6, “Setting tabs in a Text widget”.
underline Set underline=1 to underline text with this tag.
wrap How long lines are wrapped in text with this tag. See the description of the wrap option for text widgets, above.
.tag_delete(tagName, ...)

To delete one or more tags, pass their names to this method. Their options and bindings go away, and the tags are removed from all regions of text.

.tag_lower(tagName, belowThis=None)

Use this method to change the order of tags in the tag stack (see Section 24.5, “Text widget tags”, above, for an explanation of the tag stack). If you pass two arguments, the tag with name tagName is moved to a position just below the tag with name belowThis. If you pass only one argument, that tag is moved to the bottom of the tag stack.

.tag_names(index=None)

If you pass an index argument, this method returns a sequence of all the tag names that are associated with the character after that index. If you pass no argument, you get a sequence of all the tag names defined in the text widget.

.tag_nextrange(tagName, index1, index2=None)

This method searches a given region for places where a tag named tagName starts. The region searched starts at index index1 and ends at index index2. If the index2 argument is omitted, the search goes all the way to the end of the text.

If there is a place in the given region where that tag starts, the method returns a sequence [i0, i1], where i0 is the index of the first tagged character and i1 is the index of the position just after the last tagged character.

If no tag starts are found in the region, the method returns an empty string.

.tag_prevrange(tagName, index1, index2=None)

This method searches a given region for places where a tag named tagName starts. The region searched starts before index index1 and ends at index index2. If the index2 argument is omitted, the search goes all the way to the end of the text.

The return values are as in .tag_nextrange().

.tag_raise(tagName, aboveThis=None)

Use this method to change the order of tags in the tag stack (see Section 24.5, “Text widget tags”, above, for an explanation of the tag stack). If you pass two arguments, the tag with name tagName is moved to a position just above the tag with name aboveThis. If you pass only one argument, that tag is moved to the top of the tag stack.

.tag_ranges(tagName)

This method finds all the ranges of text in the widget that are tagged with name tagName, and returns a sequence [s0, e0, s1, e1, …], where each si is the index just before the first character of the range and ei is the index just after the last character of the range.

.tag_remove(tagName, index1, index2=None)

Removes the tag named tagName from all characters between index1 and index2. If index2 is omitted, the tag is removed from the single character after index1.

.tag_unbind(tagName, sequence, funcid=None)

Remove the event binding for the given sequence from the tag named tagName. If there are multiple handlers for this sequence and tag, you can remove only one handler by passing it as the third argument.

.window_cget(index, option)

Returns the value of the given option for the embedded widget at the given index.

.window_configure(index, option)

To change the value of options for embedded widget at the given index, pass in one or more option=value pairs.

If you pass only one argument, you will get back a dictionary defining all the options and their values currently in force for the given widget.

.window_create(index, option, ...)

This method creates a window where a widget can be embedded within a text widget. There are two ways to provide the embedded widget:

  1. you can use pass the widget to the window option in this method, or

  2. you can define a procedure that will create the widget and pass that procedure as a callback to the create option.

Options for .window_create() are:

align Specifies how to position the embedded widget vertically in its line, if it isn't as tall as the text on the line. Values include: align=tk.CENTER (the default), which centers the widget vertically within the line; align=tk.TOP, which places the top of the image at the top of the line; align=tk.BOTTOM, which places the bottom of the image at the bottom of the line; and align=tk.BASELINE, which aligns the bottom of the image with the text baseline.
create A procedure that will create the embedded widget on demand. This procedure takes no arguments and must create the widget as a child of the text widget and return the widget as its result.
padx Extra space added to the left and right of the widget within the text line. Default is 0.
pady Extra space added above and below the widget within the text line. Default is 0.
stretch This option controls what happens when the line is higher than the embedded widget. Normally this option is 0, meaning that the embedded widget is left at its natural size. If you set stretch=1, the widget is stretched vertically to fill the height of the line, and the align option is ignored.
window The widget to be embedded. This widget must be a child of the text widget.
.window_names()

Returns a sequence containing the names of all embedded widgets.

.xview(tk.MOVETO, fraction)

This method scrolls the text widget horizontally, and is intended for binding to the command option of a related horizontal scrollbar.

This method can be called in two different ways. The first call positions the text at a value given by fraction, where 0.0 moves the text to its leftmost position and 1.0 to its rightmost position.

.xview(tk.SCROLL, n, what)

The second call moves the text left or right: the what argument specifies how much to move and can be either tk.UNITS or tk.PAGES, and n tells how many characters or pages to move the text to the right relative to its image (or left, if negative).

.xview_moveto(fraction)

This method scrolls the text in the same way as .xview(tk.MOVETO, fraction).

.xview_scroll(n, what)

Same as .xview(tk.SCROLL, n, what).

.yview(tk.MOVETO, fraction)

The vertical scrolling equivalent of .xview(tk.MOVETO,…).

.yview(tk.SCROLL, n, what)

The vertical scrolling equivalent of .xview(tk.SCROLL,…). When scrolling vertically by tk.UNITS, the units are lines.

.yview_moveto(fraction)

The vertical scrolling equivalent of .xview_moveto().

.yview_scroll(n, what)

The vertical scrolling equivalent of .xview_scroll().