What is Text widget?

The Text Widget used to display formatted text. It is one of the most powerful widgets available in Tkinter. It allows you to display and edit text with a variety of styles and attributes.

The Text widget is useful when you want to display text documents, either containing plain text or formatted text with different attributes like font, color, images, etc.. The Text widget can also be used as a text editor.

Example

The following python script creates a window containing one text widget, It is a simple text editor. You need to write following code in any text editor and then save it with .py extension. To execute the application, Type py TextWidgetExample.py command in terminal.

from tkinter import *

# Top level window 
window = Tk()

window.title("Studyfied.com")
window.geometry('350x200')

# Create text editor
text = Text(window)
text.pack()

window.mainloop()

Output

The above code produces the following output in windows operating system.

Explanation

Following line creates a Tkinter window

from tkinter import *

window = Tk()

window.title("Studyfied.com")
window.geometry('350x200')

See explanation of Tkinter window – Tkinter top level window


This snippet creates a text editor widget, The first parameter passed in Text is parent widget, Here it is the window, You can specify more attributes and options to customize the Text widget.

# Create text editor
text = Text(window)
text.pack()

Indexes

Indexes are work like a pointer that points some position of text inside the Text widget. Similar to python sequence indexes, text widget indexes correspond to positions between the actual characters.

Different index types –

  1. line / column (“line.column”)
  2. line end (“line.end”)
  3. INSERT
  4. CURRENT
  5. END
  6. User-Defined Marks
  7. User-Defined Tags (“tag.first”, “tag.last”)
  8. Selection (SEL_FIRST, SEL_LAST)
  9. Window Coordinate (“x, y”)
  10. Embedded Object Name (window, images)
  11. Expressions

Some Text Widget properties

Property NameDescription
background / bgSets the background color for this widget. The default is system specific.
borderwidth / bdBorder width for this widget. The default is system specific but usually 1 to 2 pixels.
cursorCursor for this widget. By default, the xterm cursor is used.
foreground / fgSets the foreground color for this widget. The default is system specific.
fontFont to use for this widget. The default is system specific.
widthThe width for this widget. By default, it takes the entire available space of its parent.
heightThe height for this widget. By default, it takes the entire available space of its parent.
padxHorizontal padding to add inside the widget. The default is 1 pixel.
padyVertical padding to add inside the widget. The default is 1 pixel.
selectbackgroundSets the selection color. The default is system specific.
wrapDefines how to wrap the line. Default is CHAR