15.2. Text Manipulation

The current insertion point of a Text widget can be set using:

where index is the position to set the insertion point.

Analogous to this is the method for getting the current insertion point:
index = text.get_point()

A method that is useful in combination with the above two methods is
length = text.get_length()

which returns the current length of the Text widget. The length is the number of characters that are within the text block of the widget, including characters such as newline, which marks the end of lines.

In order to insert text at the current insertion point of a Text widget, either the insert() or insert_defaults() methods is used. The insert() method allows us to specify background and foreground colors and a font for the text. If font, fore or back are None, the corresponding widget style values are used.
text.insert(font, fore, back, string)

Using the insert_defaults() method is the same as passing a value of None in as the value for the foreground color, background color and font in the insert() method.

The text widget is one of the few within GTK that redraws itself dynamically, outside of the mainloop() function. This means that all changes to the contents of the text widget take effect immediately. This may be undesirable when performing multiple changes to the text widget. In order to allow us to perform multiple updates to the text widget without it continuously redrawing, we can freeze the widget, which temporarily stops it from automatically redrawing itself every time it is changed. We can then thaw the widget after our updates are complete.

The following two methods perform this freeze and thaw action:


Text is deleted from the text widget relative to the current insertion point by the following two methods. The return value is a TRUE or FALSE indicator of whether the operation was successful.
res = text.backward_delete(nchars)

res = text.forward_delete(nchars)

If you want to retrieve the contents of the text widget, we can use the method:
string = text.get_chars(start_pos, end_pos) 

This is a method of the parent class (GtkEditable) of the text widget. A value of -1 as end_pos signifies the end of the text. The index of the text starts at 0.

The method returns a string object containing the requested text contents.