User-editable text

While pyglet does not come with any complete GUI widgets for applications to use, it does implement many of the features required to implement interactive text editing. These can be used as a basis for a more complete GUI system, or to present a simple text entry field, as demonstrated in the examples/text_input.py example.

IncrementalTextLayout should always be used for text that can be edited by the user. This class maintains information about the placement of glyphs on screen, and so can map window coordinates to a document position and vice-versa. These methods are get_position_from_point, get_point_from_position, get_line_from_point, get_point_from_line, get_line_from_position, get_position_from_line, get_position_on_line and get_line_count.

The viewable rectangle of the document can be adjusted using a document position instead of a scrollbar using the ensure_line_visible and ensure_x_visible methods.

IncrementalTextLayout can display a current text selection by temporarily overriding the foreground and background colour of the selected text. The selection_start and selection_end properties give the range of the selection, and selection_color and selection_background_color the colors to use (defaulting to white on blue).

The Caret class implements an insertion caret (cursor) for IncrementalTextLayout. This includes displaying the blinking caret at the correct location, and handling keyboard, text and mouse events. The behaviour in response to the events is very similar to the system GUIs on Windows, Mac OS X and GTK. Using Caret frees you from using the IncrementalTextLayout methods described above directly.

The following example creates a document, a layout and a caret and attaches the caret to the window to listen for events:

import pyglet

window = pyglet.window.Window()
document = pyglet.text.document.FormattedDocument()
layout = pyglet.text.layout.IncrementalTextLayout(document, width, height)
caret = pyglet.text.caret.Caret(layout)
window.push_handlers(caret)

When the layout is drawn, the caret will also be drawn, so this example is nearly complete enough to display the user input. However, it is suitable for use when only one editable text layout is to be in the window. If multiple text widgets are to be shown, some mechanism is needed to dispatch events to the widget that has keyboard focus. An example of how to do this is given in the examples/text_input.py example program.