.. include:: headings.inc .. _TextCtrl: ========================================================================================================================================== |phoenix_title| **TextCtrl** ========================================================================================================================================== A text control allows text to be displayed and edited. It may be single line or multi-line. Notice that a lot of methods of the text controls are found in the base :ref:`TextEntry` class which is a common base class for :ref:`TextCtrl` and other controls using a single line text entry field (e.g. :ref:`ComboBox`). .. _TextCtrl-styles: |styles| Window Styles ================================ This class supports the following styles: - ``TE_PROCESS_ENTER``: The control will generate the event ``wxEVT_COMMAND_TEXT_ENTER`` (otherwise pressing Enter key is either processed internally by the control or used for navigation between dialog controls). - ``TE_PROCESS_TAB``: The control will receive ``wxEVT_CHAR`` events for ``TAB`` pressed - normally, ``TAB`` is used for passing to the next control in a dialog instead. For the control created with this style, you can still use Ctrl-Enter to pass to the next control from the keyboard. - ``TE_MULTILINE``: The text control allows multiple lines. If this style is not specified, line break characters should not be used in the controls value. - ``TE_PASSWORD``: The text will be echoed as asterisks. - ``TE_READONLY``: The text will not be user-editable. - ``TE_RICH``: Use rich text control under Win32, this allows to have more than ``64KB`` of text in the control even under Win9x. This style is ignored under other platforms. - ``TE_RICH2``: Use rich text control version 2.0 or 3.0 under Win32, this style is ignored under other platforms - ``TE_AUTO_URL``: Highlight the URLs and generate the TextUrlEvents when mouse events occur over them. This style is only supported for ``TE_RICH`` Win32 and multi-line wxGTK2 text controls. - ``TE_NOHIDESEL``: By default, the Windows text control doesn't show the selection when it doesn't have focus - use this style to force it to always show it. It doesn't do anything under other platforms. - ``HSCROLL``: A horizontal scrollbar will be created and used, so that text won't be wrapped. No effect under ``GTK1``. - ``TE_NO_VSCROLL``: For multiline controls only: vertical scrollbar will never be created. This limits the amount of text which can be entered into the control to what can be displayed in it under MSW but not under GTK2. Currently not implemented for the other platforms. - ``TE_LEFT``: The text in the control will be left-justified (default). - ``TE_CENTRE``: The text in the control will be centered (currently wxMSW and wxGTK2 only). - ``TE_RIGHT``: The text in the control will be right-justified (currently wxMSW and wxGTK2 only). - ``TE_DONTWRAP``: Same as ``HSCROLL`` style: don't wrap at all, show horizontal scrollbar instead. - ``TE_CHARWRAP``: Wrap the lines too long to be shown entirely at any position (wxUniv and wxGTK2 only). - ``TE_WORDWRAP``: Wrap the lines too long to be shown entirely at word boundaries (wxUniv and wxGTK2 only). - ``TE_BESTWRAP``: Wrap the lines at word boundaries or at any other character if there are words longer than the window width (this is the default). - ``TE_CAPITALIZE``: On PocketPC and Smartphone, causes the first letter to be capitalized. Note that alignment styles (``TE_LEFT``, ``TE_CENTRE`` and ``TE_RIGHT``) can be changed dynamically after control creation on wxMSW and wxGTK. ``TE_READONLY``, ``TE_PASSWORD`` and wrapping styles can be dynamically changed under wxGTK but not wxMSW. The other styles can be only set during control creation. |phoenix_title| TextCtrl Text Format ==================================== The multiline text controls always store the text as a sequence of lines separated by ``'\n'`` characters, i.e. in the Unix text format even on non-Unix platforms. This allows the user code to ignore the differences between the platforms but at a price: the indices in the control such as those returned by :meth:`~TextCtrl.GetInsertionPoint` or :meth:`~TextCtrl.GetSelection` can **not** be used as indices into the string returned by :meth:`~TextCtrl.GetValue` as they're going to be slightly off for platforms using ``"\\r\\n"`` as separator (as Windows does). Instead, if you need to obtain a substring between the 2 indices obtained from the control with the help of the functions mentioned above, you should use :meth:`~TextCtrl.GetRange`. And the indices themselves can only be passed to other methods, for example :meth:`~TextCtrl.SetInsertionPoint` or :meth:`~TextCtrl.SetSelection`. To summarize: never use the indices returned by (multiline) :ref:`TextCtrl` as indices into the string it contains, but only as arguments to be passed back to the other :ref:`TextCtrl` methods. This problem doesn't arise for single-line platforms however where the indices in the control do correspond to the positions in the value string. |phoenix_title| TextCtrl Styles ================================ Multi-line text controls support styling, i.e. provide a possibility to set colours and font for individual characters in it (note that under Windows ``TE_RICH`` style is required for style support). To use the styles you can either call :meth:`~TextCtrl.SetDefaultStyle` before inserting the text or call :meth:`~TextCtrl.SetStyle` later to change the style of the text already in the control (the first solution is much more efficient). In either case, if the style doesn't specify some of the attributes (for example you only want to set the text colour but without changing the font nor the text background), the values of the default style will be used for them. If there is no default style, the attributes of the text control itself are used. So the following code correctly describes what it does: the second call to :meth:`~TextCtrl.SetDefaultStyle` doesn't change the text foreground colour (which stays red) while the last one doesn't change the background colour (which stays grey): :: text.SetDefaultStyle(wx.TextAttr(wx.RED)) text.AppendText("Red text\n") text.SetDefaultStyle(wx.TextAttr(wx.NullColour, wx.LIGHT_GREY)) text.AppendText("Red on grey text\n") text.SetDefaultStyle(wx.TextAttr(wx.BLUE)) text.AppendText("Blue on grey text\n") |phoenix_title| Event Handling =============================== .. _TextCtrl-events: |events| Events Emitted by this Class ===================================== Handlers bound for the following event types will receive one of the ref:`TextCtrl`: ``ID_CUT`` , ``ID_COPY`` , ``ID_PASTE`` , ``ID_UNDO`` , ``ID_REDO`` . The associated UI update events are also processed automatically, when the control has the focus. The following event handler macros redirect the events to member function handlers '**func**' with prototypes like: :ref:`CommandEvent` parameters. - EVT_TEXT: Respond to a ``wxEVT_COMMAND_TEXT_UPDATED`` event, generated when the text changes. Notice that this event will be sent when the text controls contents changes -- whether this is due to user input or comes from the program itself (for example, if :meth:`TextCtrl.SetValue` is called); see :meth:`TextCtrl.ChangeValue` for a function which does not send this event. This event is however not sent during the control creation. - EVT_TEXT_ENTER: Respond to a ``wxEVT_COMMAND_TEXT_ENTER`` event, generated when enter is pressed in a text control which must have ``TE_PROCESS_ENTER`` style for this event to be generated. - EVT_TEXT_URL: A mouse event occurred over an ``URL`` in the text control (wxMSW and wxGTK2 only currently). - EVT_TEXT_MAXLEN: This event is generated when the user tries to enter more text into the control than the limit set by :meth:`TextCtrl.SetMaxLength` , see its description. .. seealso:: :meth:`TextCtrl.Create` , :ref:`Validator` | |class_hierarchy| Inheritance Diagram ===================================== Inheritance diagram for class **TextCtrl** .. raw:: html

Inheritance diagram of TextCtrl

| |appearance| Control Appearance =============================== | .. figure:: _static/images/widgets/fullsize/wxmsw/textctrl.png :alt: wxMSW :figclass: floatleft **wxMSW** .. figure:: _static/images/widgets/fullsize/wxmac/textctrl.png :alt: wxMAC :figclass: floatright **wxMAC** .. figure:: _static/images/widgets/fullsize/wxgtk/textctrl.png :alt: wxGTK :figclass: floatcenter **wxGTK** | |sub_classes| Known Subclasses ============================== :ref:`SearchCtrl` | |method_summary| Methods Summary ================================ ================================================================================ ================================================================================ :meth:`~TextCtrl.__init__` Default constructor. :meth:`~TextCtrl.Create` Creates the text control for two-step construction. :meth:`~TextCtrl.Cut` Copies the selected text to the clipboard and removes the selection. :meth:`~TextCtrl.DiscardEdits` Resets the internal modified flag as if the current changes had been saved. :meth:`~TextCtrl.EmulateKeyPress` This function inserts into the control the character which would have been inserted if the given key event had occurred in the text control. :meth:`~TextCtrl.GetDefaultStyle` Returns the style currently used for the new text. :meth:`~TextCtrl.GetLineLength` Gets the length of the specified line, not including any trailing newline character(s). :meth:`~TextCtrl.GetLineText` Returns the contents of a given line in the text control, not including any trailing newline character(s). :meth:`~TextCtrl.GetNumberOfLines` Returns the number of lines in the text control buffer. :meth:`~TextCtrl.GetStyle` Returns the style at this position in the text control. :meth:`~TextCtrl.HitTestPos` This function finds the character at the specified position expressed in pixels. :meth:`~TextCtrl.HitTest` This function finds the character at the specified position expressed in pixels. :meth:`~TextCtrl.IsModified` Returns ``True`` if the text has been modified by user. :meth:`~TextCtrl.IsMultiLine` Returns ``True`` if this is a multi line edit control and ``False`` otherwise. :meth:`~TextCtrl.IsSingleLine` Returns ``True`` if this is a single line edit control and ``False`` otherwise. :meth:`~TextCtrl.LoadFile` Loads and displays the named file, if it exists. :meth:`~TextCtrl.MarkDirty` Mark text as modified (dirty). :meth:`~TextCtrl.OnDropFiles` This event handler function implements default drag and drop behaviour, which is to load the first dropped file into the control. :meth:`~TextCtrl.PositionToCoords` Converts given text position to client coordinates in pixels. :meth:`~TextCtrl.PositionToXY` Converts given position to a zero-based column, line number pair. :meth:`~TextCtrl.SaveFile` Saves the contents of the control in a text file. :meth:`~TextCtrl.SetDefaultStyle` Changes the default style to use for the new text which is going to be added to the control using :meth:`WriteText` or :meth:`AppendText` . :meth:`~TextCtrl.SetModified` Marks the control as being modified by the user or not. :meth:`~TextCtrl.SetStyle` Changes the style of the given range. :meth:`~TextCtrl.ShowPosition` Makes the line containing the given position visible. :meth:`~TextCtrl.XYToPosition` Converts the given zero based column and line number to a position. ================================================================================ ================================================================================ | |property_summary| Properties Summary ===================================== ================================================================================ ================================================================================ :attr:`~TextCtrl.DefaultStyle` See :meth:`~TextCtrl.GetDefaultStyle` and :meth:`~TextCtrl.SetDefaultStyle` :attr:`~TextCtrl.NumberOfLines` See :meth:`~TextCtrl.GetNumberOfLines` ================================================================================ ================================================================================ | |api| Class API =============== .. class:: TextCtrl(Control, TextEntry) A text control allows text to be displayed and edited. **Possible constructors**:: TextCtrl() TextCtrl(parent, id=ID_ANY, value='', pos=DefaultPosition, size=DefaultSize, style=0, validator=DefaultValidator, name=TextCtrlNameStr) .. method:: __init__(self, *args, **kw) |overload| **Overloaded Implementations**: **~~~** **__init__** `(self)` Default constructor. **~~~** **__init__** `(self, parent, id=ID_ANY, value='', pos=DefaultPosition, size=DefaultSize, style=0, validator=DefaultValidator, name=TextCtrlNameStr)` Constructor, creating and showing a text control. :param `parent`: Parent window. Should not be ``None``. :type `parent`: Window :param `id`: Control identifier. A value of -1 denotes a default value. :type `id`: int :param `value`: Default text value. :type `value`: string :param `pos`: Text control position. :type `pos`: Point :param `size`: Text control size. :type `size`: Size :param `style`: Window style. See :ref:`TextCtrl`. :type `style`: long :param `validator`: Window validator. :type `validator`: Validator :param `name`: Window name. :type `name`: string .. note:: The horizontal scrollbar (``HSCROLL`` style flag) will only be created for multi-line text controls. Without a horizontal scrollbar, text lines that don't fit in the control's size will be wrapped (but no newline character is inserted). Single line controls don't have a horizontal scrollbar, the text is automatically scrolled so that the insertion point is always visible. .. seealso:: :meth:`Create` , :ref:`Validator` **~~~** .. method:: Create(self, parent, id=ID_ANY, value='', pos=DefaultPosition, size=DefaultSize, style=0, validator=DefaultValidator, name=TextCtrlNameStr) Creates the text control for two-step construction. This method should be called if the default constructor was used for the control creation. Its parameters have the same meaning as for the non-default constructor. :param `parent`: :type `parent`: Window :param `id`: :type `id`: int :param `value`: :type `value`: string :param `pos`: :type `pos`: Point :param `size`: :type `size`: Size :param `style`: :type `style`: long :param `validator`: :type `validator`: Validator :param `name`: :type `name`: string :rtype: `bool` .. method:: Cut(self) Copies the selected text to the clipboard and removes the selection. .. method:: DiscardEdits(self) Resets the internal modified flag as if the current changes had been saved. .. method:: EmulateKeyPress(self, event) This function inserts into the control the character which would have been inserted if the given key event had occurred in the text control. The `event` object should be the same as the one passed to ``EVT_KEY_DOWN`` handler previously by wxWidgets. Please note that this function doesn't currently work correctly for all keys under any platform but MSW. :param `event`: :type `event`: KeyEvent :rtype: `bool` :returns: ``True`` if the event resulted in a change to the control, ``False`` otherwise. .. method:: GetDefaultStyle(self) Returns the style currently used for the new text. :rtype: :ref:`TextAttr` .. seealso:: :meth:`SetDefaultStyle` .. method:: GetLineLength(self, lineNo) Gets the length of the specified line, not including any trailing newline character(s). :param `lineNo`: Line number (starting from zero). :type `lineNo`: long :rtype: `int` :returns: The length of the line, or -1 if `lineNo` was invalid. .. method:: GetLineText(self, lineNo) Returns the contents of a given line in the text control, not including any trailing newline character(s). :param `lineNo`: The line number, starting from zero. :type `lineNo`: long :rtype: `string` :returns: The contents of the line. .. method:: GetNumberOfLines(self) Returns the number of lines in the text control buffer. The returned number is the number of logical lines, i.e. just the count of the number of newline characters in the control + 1, for wxGTK and OSX/Cocoa ports while it is the number of physical lines, i.e. the count of lines actually shown in the control, in wxMSW and OSX/Carbon. Because of this discrepancy, it is not recommended to use this function. :rtype: `int` .. note:: Note that even empty text controls have one line (where the insertion point is), so :meth:`GetNumberOfLines` never returns 0. .. method:: GetStyle(self, position, style) Returns the style at this position in the text control. Not all platforms support this function. :param `position`: :type `position`: long :param `style`: :type `style`: TextAttr :rtype: `bool` :returns: ``True`` on success, ``False`` if an error occurred (this may also mean that the styles are not supported under this platform). .. seealso:: :meth:`SetStyle` , :ref:`TextAttr` .. method:: HitTestPos(self, pt) This function finds the character at the specified position expressed in pixels. The two overloads of this method allow to find either the position of the character, as an index into the text control contents, or its row and column. If the return code is not ``TE_HT_UNKNOWN`` the row and column of the character closest to this position are returned, otherwise the output parameters are not modified. Please note that this function is currently only implemented in Univ, wxMSW and wxGTK2 ports and always returns ``TE_HT_UNKNOWN`` in the other ports. :param `pt`: The position of the point to check, in window device coordinates. :type `pt`: Point Receives the column of the character at the given position. May be ``None``. Receives the row of the character at the given position. May be ``None``. Receives the position of the character at the given position. May be ``None``. :rtype: `tuple` :returns: ( :ref:`TextCtrlHitTestResult`, `pos` ) .. seealso:: :meth:`PositionToXY` , :meth:`XYToPosition` .. method:: HitTest(self, pt) This function finds the character at the specified position expressed in pixels. The two overloads of this method allow to find either the position of the character, as an index into the text control contents, or its row and column. If the return code is not ``TE_HT_UNKNOWN`` the row and column of the character closest to this position are returned, otherwise the output parameters are not modified. Please note that this function is currently only implemented in Univ, wxMSW and wxGTK2 ports and always returns ``TE_HT_UNKNOWN`` in the other ports. :param `pt`: The position of the point to check, in window device coordinates. :type `pt`: Point Receives the column of the character at the given position. May be ``None``. Receives the row of the character at the given position. May be ``None``. Receives the position of the character at the given position. May be ``None``. :rtype: `tuple` :returns: ( :ref:`TextCtrlHitTestResult`, `col`, `row` ) .. seealso:: :meth:`PositionToXY` , :meth:`XYToPosition` .. method:: IsModified(self) Returns ``True`` if the text has been modified by user. Note that calling :meth:`SetValue` doesn't make the control modified. :rtype: `bool` .. seealso:: :meth:`MarkDirty` .. method:: IsMultiLine(self) Returns ``True`` if this is a multi line edit control and ``False`` otherwise. :rtype: `bool` .. seealso:: :meth:`IsSingleLine` .. method:: IsSingleLine(self) Returns ``True`` if this is a single line edit control and ``False`` otherwise. :rtype: `bool` .. seealso:: :meth:`IsSingleLine` , :meth:`IsMultiLine` .. method:: LoadFile(self, filename, fileType=TEXT_TYPE_ANY) Loads and displays the named file, if it exists. :param `filename`: The filename of the file to load. :type `filename`: string :param `fileType`: The type of file to load. This is currently ignored in :ref:`TextCtrl`. :type `fileType`: int :rtype: `bool` :returns: ``True`` if successful, ``False`` otherwise. .. method:: MarkDirty(self) Mark text as modified (dirty). .. seealso:: :meth:`IsModified` .. method:: OnDropFiles(self, event) This event handler function implements default drag and drop behaviour, which is to load the first dropped file into the control. :param `event`: The drop files event. :type `event`: DropFilesEvent .. note:: This is not implemented on non-Windows platforms. .. seealso:: :ref:`DropFilesEvent` .. method:: PositionToCoords(self, pos) Converts given text position to client coordinates in pixels. This function allows to find where is the character at the given position displayed in the text control. :param `pos`: Text position in 0 to :meth:`GetLastPosition` range (inclusive). :type `pos`: long :rtype: :ref:`Point` :returns: On success returns a :ref:`Point` which contains client coordinates for the given position in pixels, otherwise returns ``DefaultPosition`` . .. versionadded:: 2.9.3 .. availability:: Only available for MSW, GTK . Additionally, wxGTK only implements this method for multiline controls and ``DefaultPosition`` is always returned for the single line ones. .. seealso:: :meth:`XYToPosition` , :meth:`PositionToXY` .. method:: PositionToXY(self, pos) Converts given position to a zero-based column, line number pair. :param `pos`: Position. :type `pos`: long Receives zero based column number. Receives zero based line number. :rtype: `tuple` :returns: ( `bool`, `x`, `y` ) .. seealso:: :meth:`XYToPosition` .. method:: SaveFile(self, filename='', fileType=TEXT_TYPE_ANY) Saves the contents of the control in a text file. :param `filename`: The name of the file in which to save the text. :type `filename`: string :param `fileType`: The type of file to save. This is currently ignored in :ref:`TextCtrl`. :type `fileType`: int :rtype: `bool` :returns: ``True`` if the operation was successful, ``False`` otherwise. .. method:: SetDefaultStyle(self, style) Changes the default style to use for the new text which is going to be added to the control using :meth:`WriteText` or :meth:`AppendText` . If either of the font, foreground, or background colour is not set in `style`, the values of the previous default style are used for them. If the previous default style didn't set them neither, the global font or colours of the text control itself are used as fall back. However if the `style` parameter is the default :ref:`TextAttr`, then the default style is just reset (instead of being combined with the new style which wouldn't change it at all). :param `style`: The style for the new text. :type `style`: TextAttr :rtype: `bool` :returns: ``True`` on success, ``False`` if an error occurred (this may also mean that the styles are not supported under this platform). .. seealso:: :meth:`GetDefaultStyle` .. method:: SetModified(self, modified) Marks the control as being modified by the user or not. :param `modified`: :type `modified`: bool .. seealso:: :meth:`MarkDirty` , :meth:`DiscardEdits` .. method:: SetStyle(self, start, end, style) Changes the style of the given range. If any attribute within `style` is not set, the corresponding attribute from :meth:`GetDefaultStyle` is used. :param `start`: The start of the range to change. :type `start`: long :param `end`: The end of the range to change. :type `end`: long :param `style`: The new style for the range. :type `style`: TextAttr :rtype: `bool` :returns: ``True`` on success, ``False`` if an error occurred (this may also mean that the styles are not supported under this platform). .. seealso:: :meth:`GetStyle` , :ref:`TextAttr` .. method:: ShowPosition(self, pos) Makes the line containing the given position visible. :param `pos`: The position that should be visible. :type `pos`: long .. method:: XYToPosition(self, x, y) Converts the given zero based column and line number to a position. :param `x`: The column number. :type `x`: long :param `y`: The line number. :type `y`: long :rtype: `long` :returns: The position value, or -1 if x or y was invalid. .. attribute:: DefaultStyle See :meth:`~TextCtrl.GetDefaultStyle` and :meth:`~TextCtrl.SetDefaultStyle` .. attribute:: NumberOfLines See :meth:`~TextCtrl.GetNumberOfLines`