An Introduction to Tkinter
前页 | Chapter 42. The Text Widget | 后页

# Methods

The `Text` widget supports the standard Tkinter Widget interface, plus the following methods:

`insert(index, text)`, `insert(index, text, tags)`

  Insert text at the given position (typically `INSERT` or `END`). If you provide one or more tags, they are attached to the new text.

  If you insert text on a mark, the mark is moved according to its gravity setting.

`delete(index)`, `delete(start, stop)`

  Delete the character (or embedded object) at the given position, or all text in the given range. Any marks within the range are moved to the beginning of the range.

`get(index)`, `get(start, stop)`

  Return the character at the given position, or all text in the given range.

`dump(index, options...)`, `dump(start, stop, options...)`

  Return a list of widget contents at the given position, or for all text in the given range. This includes tags, marks, and embedded objects. Not implemented in Python 1.5.2 and earlier.

`see(index)`, `yview(index)`

  If necessary, scroll the text widget to make sure the text at the given position is visible. The `see` method scrolls the widget only if the given position isn't visible at all, while `yview` always scrolls the widget to move the given position to the top of the window.

`index(index)`

  Return the "line.column" index corresponding to the given index.

`compare(index1, op, index2)`

  Compare the two positions, and return true if the condition held. The `op` argument is one of "<", "<=", "==", ">=", ">", or "!=" (Python's "<>" syntax is not supported).

## Methods for Marks

The following methods are used to manipulate builtin as well as user-defined marks.

`mark_set(mark, index)`

  Move the mark to the given position. If the mark doesn't exist, it is created (with gravity set to `RIGHT`). You also use this method to move the predefined `INSERT` and `CURRENT` marks.

`mark_unset(mark)`

  Remove the given mark from the widget. You cannot remove the builtin `INSERT` and `CURRENT` marks.

`index(mark)`

  Return the line/column position corresponding to the given mark (or any other index specifier; see above).

`mark_gravity(mark)`

  Return the current gravity setting for the given mark (`LEFT` or `RIGHT`).

`mark_gravity(mark, gravity)`

  Sets the gravity for the given mark. The gravity setting controls how to move the mark if text is inserted exactly on the mark. If `LEFT`, the mark is not moved if text is inserted at the mark (that is, the text is inserted just after the mark). If `RIGHT`, the mark is moved to the right end of the text (that is, the text is inserted just before the mark). The default gravity setting is `RIGHT`.

`mark_names()`

  Return a tuple containing the names of all marks used in the widget. This includes the `INSERT` and `CURRENT` marks (but not `END`, which is a special index, not a mark).

## Methods for Embedded Windows

The `Text` widget allows you to embed windows into the widget. Embedded windows occupy a single character position, and moves with the text flow.

`window_create(index, options...)`

  Insert a widget at the given position. You can either create the widget (which should be a child of the text widget itself) first, and insert it using the `window` option, or provide a callback which is called when the window is first displayed.

Table 42-2. Text Window Options

Option | Type | Description
`align` | constant | Defines how to align the window on the line. Use one of `TOP`, `CENTER`, `BOTTOM`, or `BASELINE`. The last alignment means that the bottom of the window is aligned with the text baseline - that is, the same alignment that is used for all text on the line).
`create` | callback | This callback is called when the window is first displayed by the text widget. It should create the window (as a child to the text widget), and return the resulting widget instance.
`padx, pady` | distance | Adds horizontal (vertical) padding between the window and the surrounding text. Default is 0 (no padding).
`stretch` | flag | If zero (or `OFF`), the window will be left as is also if the line is higher than the window. If non-zero (or `ON`), the window is stretched to cover the full line (in this case, the alignment is ignored).
`window` | widget | Gives the widget instance to insert into the text.

`index(window)`

  Return the line/column position corresponding to the given window (or any other index specifier; see above).

`delete(window)`

  Remove the given window from the text widget, and destroy it.

`window_cget(index, option)`

  Return the current value of the given option. If there's no window on the given position, this method raises a `TclError` exception.

`window_config(index, options...)`, `window_configure(index, options...)`

  Modifies one or more options. If there's no window on the given position, this method raises a `TclError` exception.

`window_names()`

  Return a tuple containing all windows embedded in the text widget. In 1.5.2 and earlier, this method returns the names of the widgets, rather than the widget instances. This will most likely be fixed in future versions.

  Here's how to convert the names to a list of widget instances in a portable fashion:

          windows = text.window_names()
          try:
              windows = map(text._nametowidget, windows)
          except TclError: pass

## Methods for Embedded Images

The `Text` widget allows you to embed images into the widget. Embedded images occupy a single character position, and moves with the text flow.

Note that the image interface is not available in early version of Tkinter (it's not implemented by Tk versions before 8.0). For such platforms, you can display images by embedding `Label` widgets instead.

### image_create

`image_create(index, options...)`. Insert an image at the given position. The image is given by the `image` option, and must be a Tkinter `PhotoImage` or `BitmapImage` instance (or an instance of the corresponding PIL classes).

This method doesn't work with Tk versions before 8.0.

Table 42-3. Text Image Options

Option | Type | Description
--- | --- | ---
`align` | constant | Defines how to align the image on the line. Use one of `TOP`, `CENTER`, `BOTTOM`, or `BASELINE`. The last alignment means that the bottom of the image is aligned with the text baseline -- that is, the same alignment that is used for all text on the line).
`image` | image | Gives the image instance to insert into the text.
`name` | string | Gives the name to use when referring to this image in the text widget. The default is the name of the image object (which is usually generated by Tkinter).
`padx, pady` | distance | Adds horizontal (vertical) padding between the image and the surrounding text. Default is 0 (no padding).

### index

`index(image)`. Return the line/column position corresponding to the given image (or any other index specifier; see above).

### delete

`delete(image)`. Remove the given image from the text widget, and destroy it.

### image_cget

`image_cget(index, option)`. Return the current value of the given option. If there's no image on the given position, this method raises a `TclError` exception. Not implemented in Python 1.5.2 and earlier.

### image_config

`image_config(index, options...)`, `image_configure(index, options...)`. Modifies one or more options. If there's no image on the given position, this method raises a `TclError` exception. Not implemented in Python 1.5.2 and earlier.

### image_names

`image_names()`. Return a tuple containing the names of all images embedded in the text widget. Tkinter doesn't provide a way to get the corresponding `PhotoImage` or `BitmapImage` objects, but you can keep track of those yourself using a dictionary (using `str(image)` as the key).

This method is not implemented in Python 1.5.2 and earlier.

## Methods for Tags

The following methods are used to manipulate tags and tag ranges.

### tag_add

`tag_add(tag, index)`, `tag_add(tag, start, top)`. Add tag to the character at the given position, or to the given range.

### tag_remove

`tag_remove(tag, index)`, `tag_remove(tag, start, stop)`. Remove the tag from the character at the given position, or from the given range. The information associated with the tag is not removed (not even if you use tag_remove(1.0, END)).

### tag_delete

`tag_delete(tag)`, `tag_delete(tags...)`. Remove the given tags from the widget. All style and binding information associated with the tags are also removed.

### tag_config

`tag_config(tag, options...)`, `tag_configure(tag, options...)`. Set style options for the given tag. If the tag doesn't exist, it is created.

Note that the style options are associated with tags, not text ranges. Any text having a given tag will be rendered according to its style options, even if it didn't exist when the binding was created. If a text range has several tags associated with it, the `Text` widget combines the style options for all tags. Tags towards the top of the tag stack (created later, or raised using `tag_raise`) have precedence.

### tag_cget

`tag_cget(tag, option)`. Get the current value for the given option.

### tag_bind

`tag_bind(tag, sequence, func)`, `tag_bind(tag, sequence, func, "+")`. Add an event binding to the given tag. Tag bindings can use mouse- and keyboard-related events, plus `<Enter>` and `<Leave>`. If the tag doesn't exist, it is created. Usually, the new binding replaces any existing binding for the same event sequence. The second form can be used to add the new callback to the existing binding.

Note that the new bindings are associated with tags, not text ranges. Any text having the tag will fire events, even if it didn't exist when the binding was created. To remove bindings, use `tag_remove` or `tag_unbind`.

### tag_unbind

`tag_unbind(tag, sequence)`. Remove the binding, if any, for the given tag and event sequence combination.

### tag_names

`tag_names()`. Return a tuple containing all tags used in the widget. This includes the `SEL` selection tag.

`tag_names(index)`. Return a tuple containing all tags used by the character at the given position.

### tag_nextrange

`tag_nextrange(tag, index)`, `tag_nextrange(tag, start, stop)`. Find the next occurence of the given tag, starting at the given index. If two indexes are given, search only from `start` to `stop`. Note that this method looks for the start of a range, so if you happen to start on a character that has the given tag, this method will return that range only if that character is the first in the range. Otherwise, the current range is skipped.

### tag_prevrange

`tag_prevrange(tag, index)`, `tag_prevrange(tag, start, stop)`. Find the next occurence of the given tag, starting at the given index and searching towards the beginning of the text. If two indexes are given, search from start to stop. As for `nextrange`, this method looks for the start of a range, beginning at the start index. So if you start on a character that has the given tag, this method will return that range unless the search started on the first character in that tag range.

### tag_lower

`tag_lower(tag)`, `tag_lower(tag, below)`. Move the given tag to the bottom of the tag stack (or place it just under the below tag). If multiple tags are defined for a range of text, options defined by tags towards the top of the stack have precedence.

### tag_raise

`tag_raise(tag)`, `tag_raise(tag, above)`. Move the given tag to the top of the tag stack (or place it just over the above tag).

### tag_ranges

`tag_ranges(tag)`. Return a tuple with start- and stop-indexes for each occurence of the given tag. If the tag doesn't exist, this method returns an empty tuple. Note that the tuple contains two items for each range.

## Methods for Selections

To manipulate the selection, use tag methods like `tag_add` and `tag_remove` on the `SEL` tag. There are no selection-specific methods provided by the `Text` widget.

But if you insist, here's how how to emulate the `Entry` widget selection methods:

        def selection_clear(text):
            text.tag_remove(SEL, 1.0, END)

        def selection_from(text, index):
            text._anchor = index

        def selection_present(text):
            return len(text.tag_ranges(SEL)) != 0

        def selection_range(text, start, end):
            text.tag_remove(SEL, 1.0, start)
            text.tag_add(SEL, start, end)
            text.tag_remove(SEL, end, END)

        def selection_to(text, index):
            if text.compare(index, "<", text._anchor):
                selection_range(text, index, text._anchor)
            else:
                selection_range(text, text._anchor, index)

## Methods for Rendering

The following methods only work if the text widget is updated. To make sure this is the case, call the `update_idletasks` method before you use any of these.

### bbox

`bbox(index)`. Returns the bounding box for the given character, as a 4-tuple: (`x, y, width, height`). If the character is not visible, this method returns None.

### dlineinfo

`dlineinfo(index)`. Returns the bounding box for the line containing the given character, as a 5-tuple: (`x, y, width, height, offset`). The last tuple member is the offset from the top of the line to the baseline. If the line is not visible, this method returns None.

## Methods for Printing

The Text widget doesn't contain any builtin support for printing. To print the contents, use `get` or `dump` and pass the resulting text to a suitable output device.

If you have a Postscript printer, you can use PIL's `PSDraw` module.

## Methods for Searching

### search

`search(pattern, index, options...)`. Search for text in the widget. Returns the first matching position if successful, or an empty string if there was no match.

Table 42-4. Text Search Options

Option | Type | Description
`forwards, backwards` | flag | Search from the given position towards the end of the buffer (`forwards`), or the beginning (`backwards`). Default is `forwards`.
`exact, regexp` | flag | Interpret the pattern as a literal string (`exact`), or a Tcl-style regular expression (`regexp`). Default is `exact`.
`nocase` | flag | Enable case-insensitive search. Default is case sensitive.
`stopindex` | index | Don't search beyond this position. Default is to search the whole buffer, and wrap around if the search reaches the end of the buffer. To prevent wrapping, set `stopindex` to `END` when searching forwards, and `1.0` when searching backwards.
`count` | variable | Return the length of the match in the given variable. If given, this variable should be a Tkinter `IntVar`.

## Methods for Scrolling

These methods are used to scroll the text widget in various ways. The `scan` methods can be used to implement fast mouse pan/roam operations (they are bound to the middle mouse button, if available), while the `xview` and `yview` methods are used with standard scrollbars.

### scan_mark, scan_dragto

`scan_mark(x, y)`, `scan_dragto(x, y)`. `scan_mark` sets the scanning anchor for fast horizontal scrolling to the given mouse coordinate. `scan_dragto` scrolls the widget contents sideways according to the given mouse coordinate. The text is moved 10 times the distance between the scanning anchor and the new position.

### xview, yview

`xview()`, `yview()`. Returns a tuple containing two values; the first value corresponds to the relative offset of the first visible line (column), and the second corresponds to the relative offset of the line (column) just after the last one visible on the screen. Offset 0.0 is the beginning of the text, 1.0 the end.

### xview, yview

`xview(MOVETO, offset)`, `yview(MOVETO, offset)`. Adjust the text widget so that the given offset is at the left (top) edge of the text. Offset 0.0 is the beginning of the text, 1.0 the end. These methods are used by the `Scrollbar` bindings when the user drags the scrollbar slider.

The `MOVETO` constant is not defined in Python 1.5.2 and earlier. For compatibility, use the string "moveto" instead.

### xview, yview

`xview(SCROLL, step, what)`, `yview(SCROLL, step, what)`. Scroll the text widget horizontally (vertically) by the given amount. The what argument can be either `UNITS` (lines, characters) or `PAGES`. These methods are used by the `Scrollbar` bindings when the user clicks at a scrollbar arrow or in the trough.

These constants are not defined in Python 1.5.2 and earlier. For compatibility, use the strings "scroll", "units", and "pages" instead.

### yview_pickplace

`yview_pickplace(index)`. Same as `see`, but only handles the vertical position correctly. New code should use `see` instead.

前页 | Home | 后页
Patterns | Up | Options