TextBox

Warning

TextBox is deprecated. Please use TextBox2 instead which supports similar editable high-performance rendering of text but also supports non-monospaced fonts and a wider range of formatting and alignment options. This is a lazy-imported class, therefore import using full path from psychopy.visual.textbox import TextBox when inheriting from it.

Attributes

TextBox([window, text, font_name, bold, ...])

Similar to the visual.TextStim component, TextBox can be used to display text within a psychopy window.

The following `set______()` attributes all have equivalent `get______()` attributes:

TextBox.setText(text_source)

Set the text to be displayed within the Textbox.

TextBox.setPosition(pos)

Set the (x,y) position of the TextBox on the Monitor.

TextBox.setHorzAlign(v)

Specify how the horizontal (x) component of the TextBox position is to be interpreted.

TextBox.setVertAlign(v)

Specify how the vertical (y) component of the TextBox position is to be interpreted.

TextBox.setHorzJust(v)

Specify how text within the TextBox should be aligned horizontally.

TextBox.setVertJust(v)

Specify how text within the TextBox should be aligned vertically.

TextBox.setFontColor(c)

Set the color to use when drawing text glyphs within the TextBox.

TextBox.setBorderColor(c)

Set the color to use for the border of the textBox.

TextBox.setBackgroundColor(c)

Set the fill color used to fill the rectangular area of the TextBox stim.

TextBox.setTextGridLineColor(c)

Set the color used when drawing text grid lines.

TextBox.setTextGridLineWidth(c)

Set the stroke width (in pixels) to use for the text grid character bounding boxes.

TextBox.setInterpolated(interpolate)

Specify whether interpolation should be enabled for the TextBox when it is drawn.

TextBox.setOpacity(o)

Sets the TextBox transparency level to use for color related attributes of the Textbox.

TextBox.setAutoLog(v)

Specify if changes to textBox attribute values should be logged automatically by PsychoPy.

TextBox.draw()

Draws the TextBox to the back buffer of the graphics card.

TextBox also provides the following read-only functions:

TextBox.getSize()

Return the width,height of the TextBox, using the unit type being used by the stimulus.

TextBox.getName()

Same as the GetLabel method.

TextBox.getDisplayedText()

Return the text that fits within the TextBox and therefore is actually seen. This is equal to::.

TextBox.getValidStrokeWidths()

Returns the stroke width range supported by the graphics card being used.

TextBox.getLineSpacing()

Return the additional spacing being applied between rows of text.

TextBox.getGlyphPositionForTextIndex(char_index)

For the provided char_index, which is the index of one character in

TextBox.getTextGridCellPlacement()

Returns a 3D numpy array containing position information for each text grid cell in the TextBox.

Helper Functions

getFontManager()

FontManager provides a simple API for finding and loading font files (.ttf) via the FreeType library.

The FontManager finds supported font files on the computer and initially creates a dictionary containing the information about available fonts. This can be used to quickly determine what font family names are available on the computer and what styles (bold, italic) are supported for each family.

This font information can then be used to create the resources necessary to display text using a given font family, style, size, color, and dpi.

The FontManager is currently used by the psychopy.visual.TextBox stim type. A user script can access the FontManager via:

font_mngr=visual.textbox.getFontManager()

Once a font of a given size and dpi has been created; it is cached by the FontManager and can be used by all TextBox instances created within the experiment.

Details

class psychopy.visual.TextBox(window=None, text='Default Test Text.', font_name=None, bold=False, italic=False, font_size=32, font_color=(0, 0, 0, 1), dpi=72, line_spacing=0, line_spacing_units='pix', background_color=None, border_color=None, border_stroke_width=1, size=None, textgrid_shape=None, pos=(0.0, 0.0), align_horz='center', align_vert='center', units='norm', grid_color=None, grid_stroke_width=1, color_space='rgb', opacity=1.0, grid_horz_justification='left', grid_vert_justification='top', autoLog=True, interpolate=False, name=None)[source]

Similar to the visual.TextStim component, TextBox can be used to display text within a psychopy window. TextBox and TextStim each have different strengths and weaknesses. You should select the most appropriate text component type based on how it will be used within the experiment.

NOTE: As of PsychoPy 1.79, TextBox should be considered experimental. The two TextBox demo scripts provided have been tested on all PsychoPy supported OS’s and run without exceptions. However there are very likely bugs in the existing TextBox code and the TextBox API will be further enhanced and improved (i.e. changed) over the next couple months.

TextBox Features

  • Text character placement is very well defined, useful when the exact positioning of each letter needs to be known.

  • The text string that is displayed can be changed ( setText() ) and drawn ( win.draw() ) very quickly. See the TextBox vs. TextStim comparison table for details.

  • Built-in font manager; providing easy access to the font family names and styles that are available on the computer being used.

  • TextBox is a composite stimulus type, with the following graphical elements, many of which can be changed to control many aspects of how the TextBox is displayed.:

    • TextBox Border / Outline

    • TextBox Fill Area

    • Text Grid Cell Lines

    • Text Glyphs

  • When using ‘rgb’ or ‘rgb255’ color spaces, colors can be specified as a list/tuple of 3 elements (red, green, blue), or with four elements (reg, green, blue, alpha) which allows different elements of the TextBox to use different opacity settings if desired. For colors that include the alpha channel value, it will be applied instead of the opacity setting of the TextBox, effectively overriding the stimulus defined opacity for that part of the textbox graphics. Colors that do not include an alpha channel use the opacity setting as normal.

  • Text Line Spacing can be controlled.

Textbox Limitations

  • Only Monospace Fonts are supported.

  • TextBox component is not a completely standard psychopy visual stim and has the following functional difference:

    • TextBox attributes are never accessed directly; get* and set* methods are always used (this will be changed to use class properties in the future).

    • Setting an attribute of a TextBox only supports value replacement, ( textbox.setFontColor([1.0,1.0,1.0]) ) and does not support specifying operators.

  • Some key word arguments supported by other stimulus types in general, or by TextStim itself, are not supported by TextBox. See the TextBox class definition for the arguments that are supported.

  • When a new font, style, and size are used it takes about 1 second to load and process the font. This is a one time delay for a given font name, style, and size. After first being loaded, the same font style can be used or re-applied to multiple TextBox components with no significant delay.

  • Auto logging or auto drawing is not currently supported.

TextStim and TextBox Comparison:

Feature

TextBox

TextStim

Change text + redraw time^

1.513 msec

28.537 msec

No change + redraw time^

0.240 msec

0.931 msec

Initial Creation time^

0.927 msec

0.194 msec

MonoSpace Font Support

Yes

Yes

Non MonoSpace Font Support

No

Yes

Adjustable Line Spacing

Yes

No

Precise Text Pos. Info

Yes

No

Auto logging Support

No

Yes

Rotation Support

No

Yes

Word Wrapping Support

Yes

Yes

^ Times are in msec.usec format. Tested using the textstim_vs_textbox.py

demo script provided with the PsychoPy distribution. Results are dependent on text length, video card, and OS. Displayed results are based on 120 character string with an average of 24 words. Test computer used Windows 7 64 bit, PsychoPy 1.79, with a i7 3.4 Ghz CPU, 8 GB RAM, and NVIDIA 480 GTX 2GB graphics card.

Example:

from psychopy import visual

win=visual.Window(...)

# A Textbox stim that will look similar to a TextStim component

textstimlike=visual.TextBox(
    window=win,
    text="This textbox looks most like a textstim.",
    font_size=18,
    font_color=[-1,-1,1],
    color_space='rgb',
    size=(1.8,.1),
    pos=(0.0,.5),
    units='norm')

# A Textbox stim that uses more of the supported graphical features
#
textboxloaded=visual.TextBox(
    window=win
    text='TextBox showing all supported graphical elements',
    font_size=32,
    font_color=[1,1,1],
    border_color=[-1,-1,1], # draw a blue border around stim
    border_stroke_width=4, # border width of 4 pix.
    background_color=[-1,-1,-1], # fill the stim background
    grid_color=[1,-1,-1,0.5], # draw a red line around each
                              # possible letter area,
                              # 50% transparent
    grid_stroke_width=1,  # with a width of 1 pix
    textgrid_shape=[20,2],  # specify area of text box
                            # by the number of cols x
                            # number of rows of text to support
                            # instead of by a screen
                            # units width x height.
    pos=(0.0,-.5),
    # If the text string length < num rows * num cols in
    # textgrid_shape, how should text be justified?
    #
    grid_horz_justification='center',
    grid_vert_justification='center')

textstimlike.draw()
textboxloaded.draw()
win.flip()
draw()[source]

Draws the TextBox to the back buffer of the graphics card. Then call win.flip() to display the changes drawn. If draw() is not called prior to a call to win.flip(), the textBox will not be displayed for that retrace.

getAutoLog()[source]

Indicates if changes to textBox attribute values should be logged automatically by PsychoPy. Currently not supported by TextBox.

getBackgroundColor()[source]

Get the color used to fill the rectangular area of the TextBox stim. All other graphical elements of the TextBox are drawn on top of the background.

getBorderColor()[source]

A border can be drawn around the perimeter of the TextBox. This method sets the color of that border.

getBorderWidth()[source]

Get the stroke width of the optional TextBox area outline. This is always given in pixel units.

getColorSpace()[source]

Returns the psychopy color space used when specifying colors for the TextBox. Supported values are:

  • ‘rgb’

  • ‘rbg255’

  • ‘norm’

  • hex (implicit)

  • html name (implicit)

See the Color Space section of the PsychoPy docs for details.

getDisplayedText()[source]

Return the text that fits within the TextBox and therefore is actually seen. This is equal to:

text_length=len(self.getText())
cols,rows=self.getTextGridShape()

displayed_text=self.getText()[0:min(text_length,rows*cols]
getFontColor()[source]

Return the color used when drawing text glyphs.

getFontSize()[source]
getGlyphPositionForTextIndex(char_index)[source]
For the provided char_index, which is the index of one character in

the current text being displayed by the TextBox ( getDisplayedText() ), return the bounding box position, width, and height for the associated glyph drawn to the screen. This factors in the glyphs position within the textgrid cell it is being drawn in, so the returned bounding box is for the actual glyph itself, not the textgrid cell. For textgrid cell placement information, see the getTextGridCellPlacement() method.

The glyph position for the given text index is returned as a tuple (x,y,width,height), where x,y is the top left hand corner of the bounding box.

Special Cases:

  • If the index provided is out of bounds for the currently displayed text, None is returned.

  • For u’ ‘ (space) characters, the full textgrid cell bounding box is returned.

  • For u’

‘ ( new line ) characters,the textgrid cell bounding box

is returned, but with the box width set to 0.

getHorzAlign()[source]

Return what textbox x position should be interpreted as. Valid options are ‘left’, ‘center’, or ‘right’ .

getHorzJust()[source]

Return how text should laid out horizontally when the number of columns of each text grid row is greater than the number needed to display the text for that text row.

getInterpolated()[source]

Returns whether interpolation is enabled for the TextBox when it is drawn. When True, GL_LINE_SMOOTH and GL_POLYGON_SMOOTH are enabled within OpenGL; otherwise they are disabled.

getLabel()[source]

Return the label / name assigned to the textbox. This does not impact how the stimulus looks when drawn, and instead is used for internal purposes only.

getLineSpacing()[source]

Return the additional spacing being applied between rows of text. The value is in units specified by the textbox getUnits() method.

getName()[source]

Same as the GetLabel method.

getOpacity()[source]

Get the default TextBox transparency level used for color related attributes. 0.0 equals fully transparent, 1.0 equals fully opaque.

getPosition()[source]

Return the x,y position of the textbox, in getUnitType() coord space.

getSize()[source]

Return the width,height of the TextBox, using the unit type being used by the stimulus.

getText()[source]

Return the text to display.

getTextGridCellForCharIndex(char_index)[source]
getTextGridCellPlacement()[source]

Returns a 3D numpy array containing position information for each text grid cell in the TextBox. The array has the shape (num_cols, num_rows, cell_bounds), where num_cols is the number of textgrid columns in the TextBox. num_rows is the number of textgrid rows in the TextBox. cell_bounds is a 4 element array containing the (x pos, y pos, width, height) data for the given cell. Position fields are for the top left hand corner of the cell box. Column and Row indices start at 0.

To get the shape of the textgrid in terms of columns and rows, use:

cell_pos_array=textbox.getTextGridCellPlacement()
col_row_count=cell_pos_array.shape[:2]

To access the position, width, and height for textgrid cell at column 0 and row 0 (so the top left cell in the textgrid):

cell00=cell_pos_array[0,0,:]

For the cell at col 3, row 1 (so 4th cell on second row):

cell41=cell_pos_array[4,1,:]
getTextGridLineColor()[source]

Return the color used when drawing the outline of the text grid cells. Each letter displayed in a TextBox populates one of the text cells defined by the shape of the TextBox text grid. Color value must be valid for the color space being used by the TextBox.

A value of None indicates drawing of the textgrid lines is disabled.

getTextGridLineWidth()[source]

Return the stroke width (in pixels) of the optional lines drawn around the text grid cell areas.

getUnitType()[source]

Returns which of the psychopy coordinate systems are used by the TextBox. Position and size related attributes mush be specified relative to the unit type being used. Valid options are:

  • pix

  • norm

  • cm

getValidStrokeWidths()[source]

Returns the stroke width range supported by the graphics card being used. If the TextBox is Interpolated, a tuple is returns using float values, with the following structure:

((min_line_width, max_line_width), line_width_granularity)

If Interpolation is disabled for the TextBox, the returned tuple elements are int values, with the following structure:

(min_line_width, max_line_width)

getVertAlign()[source]

Return what textbox y position should be interpreted as. Valid options are ‘top’, ‘center’, or ‘bottom’ .

getVertJust()[source]

Return how text should laid out vertically when the number of text grid rows is greater than the number needed to display the current text

getWindow()[source]

Returns the psychopy window that the textBox is associated with.

setAutoLog(v)[source]

Specify if changes to textBox attribute values should be logged automatically by PsychoPy. True enables auto logging; False disables it. Currently not supported by TextBox.

setBackgroundColor(c)[source]

Set the fill color used to fill the rectangular area of the TextBox stim. Color value must be valid for the color space being used by the TextBox.

A value of None will disable drawing of the TextBox background.

setBorderColor(c)[source]

Set the color to use for the border of the textBox. The TextBox border is a rectangular outline drawn around the edges of the TextBox stim. Color value must be valid for the color space being used by the TextBox.

A value of None will disable drawing of the border.

setBorderWidth(c)[source]

Set the stroke width (in pixels) to use for the border of the TextBox stim. Border values must be within the range of stroke widths supported by the OpenGL driver used by the graphics. Setting the width outside the valid range will result in the stroke width being clamped to the nearest end of the valid range.

Use the TextBox.getValidStrokeWidths() to access the minimum - maximum range of valid line widths.

setFontColor(c)[source]

Set the color to use when drawing text glyphs within the TextBox. Color value must be valid for the color space being used by the TextBox. For ‘rgb’, ‘rgb255’, and ‘norm’ based colors, three or four element lists are valid. Three element colors use the TextBox getOpacity() value to determine the alpha channel for the color. Four element colors use the value of the fourth element to set the alpha value for the color.

setHorzAlign(v)[source]

Specify how the horizontal (x) component of the TextBox position is to be interpreted. left = x position is the left edge, right = x position is the right edge x position, and center = the x position is used to center the stim horizontally.

setHorzJust(v)[source]

Specify how text within the TextBox should be aligned horizontally. For example, if a text grid has 10 columns, and the text being displayed is 6 characters in length, the horizontal justification determines if the text should be draw starting at the left of the text columns (left), or should be centered on the columns (‘center’, in this example there would be two empty text cells to the left and right of the text.), or should be drawn such that the last letter of text is drawn in the last column of the text row (‘right’).

setInterpolated(interpolate)[source]

Specify whether interpolation should be enabled for the TextBox when it is drawn. When interpolate == True, GL_LINE_SMOOTH and GL_POLYGON_SMOOTH are enabled within OpenGL. When interpolate is set to False, GL_POLYGON_SMOOTH and GL_LINE_SMOOTH are disabled.

setOpacity(o)[source]

Sets the TextBox transparency level to use for color related attributes of the Textbox. 0.0 equals fully transparent, 1.0 equals fully opaque.

If opacity is set to None, it is assumed to have a default value of 1.0.

When a color is defined with a 4th element in the colors element list, then this opacity value is ignored and the alpha value provided in the color itself is used for that TextGrid element instead.

setPosition(pos)[source]

Set the (x,y) position of the TextBox on the Monitor. The position must be given using the unit coord type used by the stim.

The TextBox position is interpreted differently depending on the Horizontal and Vertical Alignment settings of the stim. See getHorzAlignment() and getVertAlignment() for more information.

For example, if the TextBox alignment is specified as left, top, then the position specifies the top left hand corner of where the stim will be drawn. An alignment of bottom,right indicates that the position value will define where the bottom right corner of the TextBox will be drawn. A horz., vert. alignment of center, center will place the center of the TextBox at pos.

setText(text_source)[source]

Set the text to be displayed within the Textbox.

Note that once a TextBox has been created, the number of character rows and columns is static. To change the size of a TextBox, a new TextBox stim must be created to replace the current Textbox stim. Therefore ensure that the textbox is large enough to display the largest length string to be presented in the TextBox. Characters that do not fit within the TextBox will not be displayed.

Color value must be valid for the color space being used by the TextBox.

setTextGridLineColor(c)[source]

Set the color used when drawing text grid lines. These are lines that can be drawn which mark the bounding box for each character within the TextBox text grid. Color value must be valid for the color space being used by the TextBox.

Provide a value of None to disable drawing of textgrid lines.

setTextGridLineWidth(c)[source]

Set the stroke width (in pixels) to use for the text grid character bounding boxes. Border values must be within the range of stroke widths supported by the OpenGL driver used by the computer graphics card. Setting the width outside the valid range will result in the stroke width being clamped to the nearest end of the valid range.

Use the TextBox.getGLineRanges() to access a dict containing some OpenGL parameters which provide the minimum, maximum, and resolution of valid line widths.

setVertAlign(v)[source]

Specify how the vertical (y) component of the TextBox position is to be interpreted. top = y position is the top edge, bottom = y position is the bottom edge y position, and center = the y position is used to center the stim vertically.

setVertJust(v)[source]

Specify how text within the TextBox should be aligned vertically. For example, if a text grid has 3 rows for text, and the text being displayed all fits on one row, the vertical justification determines if the text should be draw on the top row of the text grid (top), or should be centered on the rows (‘center’, in this example there would be one row above and below the row used to draw the text), or should be drawn on the last row of the text grid, (‘bottom’).


Back to top