Within Tkinter, there are text boxes that allow the entry or viewing of text. The text can be newly entered or edited by the user.
From the programming side, you can format the text as you wish. There is the use of colors, fonts, etc. Keep in mind that the Text Object can be a single line of text or multi-line.
Some of these parameters are basic ones that we've seen before, so we will pass over them with examples because they are general options that nearly all objects use.
Let's look at creating a text box.
Create a Text Object
The way to create a Text Object and place it:
Since we did not specify any settings, the Text Object is a multi-line box as shown in Figure 1.
FIGURE 1
By default, it will go to the main window, which we usually call 'root'. You can change that with:
Here, you can specify the window name for the location of the Text Object.
Let's look into the various parameters we can pass to the widget before we get into the methods that we can use on the object.
Background Color
To set the background color other than the default of gray, you can use the parameter 'bg':
The parameter is used in the same was as other widgets to set a background color.
Border Width
The border width of a Text Object is 2 pixels, but you can change this:
Whatever value you give is in pixels.
The values used should be 0 (no border) to a higher value that will create a thicker border the higher the number. Negative numbers will create a border inside the original border placement. This means that it can start covering text within the Text Object.
Cursor
This parameter lets you specify the type of cursor that appears when the user moves the cursor into the Text Widget.
You can see the full list of cursors in the article 'Python 17 - Labels'.
The default used is 'xterm', such as:
Selection
With the mouse, you can select or highlight text. We can manage the selected text as needed.
If a user selects text and then moves to another widget, the selected text is unselected. If you want to not allow the selection to be removed when it loses focus to another Text Widget, then use the parameter:
Font
You can specify the font that is displayed in the Text Object. Be sure that the font is available on the system, especially if the Python script is copied to another system.
The syntax is:
You can also set the font size and style:
Be aware that if the font size is changed, it also changes the size of the Text Object.
To see the styles, see 'Python 18 - Buttons'.
Foreground Color
As with other widgets, we can set the foreground color, or the text color.
If we wanted the text color purple, we could use:
Height
This is the height of the Text Object, in lines, according to the font size.
An example:
There is no defined default. The setting is determined dynamically based on the font and font size used.
Highlight Background
This is the color of the border, if one exists, when the Text Widget loses focus. Let me give a coding example:
Here, if you click on the Entry Object at the bottom, you can see that the border of the Text Object becomes blue. When you click back on the Text Object, and give it focus, the border color changes back to black.
Highlight Color
Here, we can set the border color when the object has the focus.
So, we can set both 'highlightcolor' and 'highlightbackground' at the same time:
It is more noticeable if the width is more than the default of 2 pixels, but the 'bd' parameter has no effect on the highlight. To change the thickness of the highlight, use 'highlightthickness'.
Highlight Thickness
Here, we can set the thickness of the highlighted line around the Text Object. The default width is 1 pixel.
If you do not want any highlighted area, then set the value equal to 0.
To make it a little bigger than the default:
Insert Background
This parameter lets you set the background color of the insertion cursor. The default is black.
Once you click on the Text Widget, a blinking cursor appears. Usually, it is black. You can change the color, for instance, to blue:
You can change the blinking cursor to be whatever color you wish. Be careful not to make it too similar to the background or it will seem it does not exist.
Insert Border Width
This is the border width around the insertion cursor. By default, it is set to 0.
We can show an example of changing the insertion cursor to blue and a border width of 2 pixels:
Insert Off Time
This is the number of milliseconds that the blinking insertion cursor is off. The default value is 300 milliseconds. Keep in mind that the default time that the cursor is on is set to 600 milliseconds.
Setting the parameter to zero will cause the insertion cursor to not blink.
Be careful not to have the cursor 'off' for a lengthy amount of time, or it will seem as the cursor disappeared.
Insert On Time
Just like 'insertofftime', this option controls the cursor blink time. The amount is in milliseconds and specifies how long the insertion cursor is visible before it turns off. The default is 600 milliseconds.
You can also set this option to zero, but the cursor will not blink at all or be visible.
Insert Width
The 'insertwidth' is the actual width of the insertion cursor itself. The default is 2 pixels, while the height is the tallest item in the line.
If you change the font size, then the insertion cursor will change as well.
This works well, but when the insertion cursor is at the leftmost position, the width looks like the default until you move it to the right.
Padx
You can add padding to add an area, or margin, to the left and right of the text area. The default is one pixel.
Even with padding, the insertion cursor appears as one pixel when at the leftmost position.
The padding helps make the text not appear to be crushed up against the Text Widget border.
Pady
It is possible to add padding at the top and bottom of the text within the Text Widget. The default is one pixel, and if you increase it, there will be more space between the border and the text.
Using padding can help make the Text Object more visually pleasing by not looking like the text is close to the edge.
Relief
There are six different border styles that can be used. The default is 'SUNKEN', but you can see the various reliefs available in Figure 3 of the 'Python 17 - Labels'.
Look at the picture to see the difference between the various types.
Select Background
When you select text, you can specify the color of the selected background. The default is usually light gray.
You can use any of the available colors; just try a color to make sure it is still readable when selected. An example is to make the selected background 'red':
Select Border Width
Selected text has a border around it. You can specify the width of the selected text border.
With a border of 4, as shown in the example and followed by Figure 2:
FIGURE 2
The default border size of selected text is two pixels.
Spacing1
This is the spacing, measured in pixels, that is added before each paragraph. If a line wraps, then it is still the same paragraph and no extra spacing is placed above the line. The default is 0.
The example would place 3 pixels above each paragraph.
Spacing2
Unlike 'spacing1', the option for 'spacing2' places a vertical space between lines that wrap. The measurement is in pixels. The default is 0, so there is no vertical spacing placed between lines of the same paragraph, except going to the next line.
The example would place 3 pixels above each line within the same paragraph that wraps to the next line.
Spacing3
This option sets the spacing that is placed after the last line of a paragraph. The spacing is used even if the line does not wrap.
You can use this method to space out the lines a little so they do not look so scrunched up.
The default spacing for 'spacing3' is 0.
The example places a space of 5 pixels between each line of text in the Text Object.
State
If you want the Text Widget to support events from the keyboard and mouse, then you need to set this option to 'NORMAL'.
If you do not want any events to be performed on the object, then:
This basically means that the Text Object is disabled and you cannot enter text or perform any operations on the object. You can still select text with the mouse, but for all purposes, the text is read-only.
Tabs
The option lets you set how a tab controls text. When the tab key is pressed, it advances one character.
You can specify the distance that a tab moves. The measurements are:
Width
The width of the Text Object in characters. The size will be reflected in the font and font size. If you enlarge the font size, then the Text Widget will change in size as well.
Keep in mind that this is in characters, like the option 'height'. The two options used together will help set a size for your Text Widget.
There is no defined default. The setting is determined dynamically based on the font and font size used.
Wrap
We have used the word 'wrap' previously. There are three choices about how to handle the placement of letters and words when a line is too long for the width of the Text Object. The settings are:
Choosing 'CHAR' will cause the line to be filled to the end, and the next character that will not fit is placed on the next line. This can cause words to be broken up between lines.
By default, the option is set to 'CHAR'.
As you can see in Figure 3, the top Text Widget is wrapped by word and the lower Text Object is wrapped by character.
FIGURE 3
By setting 'wrap' to "none", the text will not wrap at all, but be on one line and go out of the Text Object. To view it, you would need to use the keyboard arrow keys after selecting an insertion point, or select text with the mouse and let is scroll the text.
X Scroll Command
When the text goes out of the screen, we are left with few choices to see the text that is not visible. With the 'xscrollcommand', we can have a scrollbar to move the visible text horizontally.
I know that we have not covered using scroll bars yet, but this will be a crash course into some basics of scroll bars.
Here, there should be three lines that may look unfamiliar. These three lines are:
The first line sets up a vertical scrollbar named 'xscrollbar'. When activated, the command 't1.xview' is executed. This will change the view of the Text Box (T1) horizontally.
The second line is just placing the vertical scrollbar onto the window.
Finally, the last line is used to set the view when the scrollbar is moved to match the movement of the scrollbar.
Y Scroll Command
This option is like the 'xscrollcommand', but vertically managed.
After the last example, I will show an example of a vertical scrollbar:
I changed the wrap option to 'WORD' as well as changing the object size. This will force the object to be required to scroll up and down to see all the text. Also, the text being inserted into the Text Object was duplicated for three identical sentences in one paragraph.
Embedding Image
Before we get to the Text Widget Methods, we need to cover one last ability of the Text Object; which is embedding an image into the object.
The following two lines are used to load an image and then place the image into the Text Object:
The PNG file can be any you have, but keep in mind that it needs to fit into the Text Object. If the image is large, then it may not fit into the Widget properly.
The second line will create the image into the Text Object (t1) and place it at the end of the text. You can place more text after the image if needed.
Be sure to test the image to verify it loads as well as fits in the object.
Conclusion
This covers the use of the standard options for the Text Widget for Tkinter.
I hope you find these options usable, but be sure to check out the next part for covering Methods, Tags and Marks.
From the programming side, you can format the text as you wish. There is the use of colors, fonts, etc. Keep in mind that the Text Object can be a single line of text or multi-line.
Some of these parameters are basic ones that we've seen before, so we will pass over them with examples because they are general options that nearly all objects use.
Let's look at creating a text box.
Create a Text Object
The way to create a Text Object and place it:
Code:
t1=Text()
t1.grid(column=0, row=0)
Since we did not specify any settings, the Text Object is a multi-line box as shown in Figure 1.
FIGURE 1
By default, it will go to the main window, which we usually call 'root'. You can change that with:
Code:
t1=Text(window)
Here, you can specify the window name for the location of the Text Object.
Let's look into the various parameters we can pass to the widget before we get into the methods that we can use on the object.
Background Color
To set the background color other than the default of gray, you can use the parameter 'bg':
Code:
t1=Text(bg="blue")
The parameter is used in the same was as other widgets to set a background color.
Border Width
The border width of a Text Object is 2 pixels, but you can change this:
Code:
t1=Text(bd=4)
Whatever value you give is in pixels.
The values used should be 0 (no border) to a higher value that will create a thicker border the higher the number. Negative numbers will create a border inside the original border placement. This means that it can start covering text within the Text Object.
Cursor
This parameter lets you specify the type of cursor that appears when the user moves the cursor into the Text Widget.
You can see the full list of cursors in the article 'Python 17 - Labels'.
The default used is 'xterm', such as:
Code:
t1=Text(cursor="xterm")
Selection
With the mouse, you can select or highlight text. We can manage the selected text as needed.
If a user selects text and then moves to another widget, the selected text is unselected. If you want to not allow the selection to be removed when it loses focus to another Text Widget, then use the parameter:
Code:
t1=Text(exportselection=0)
Font
You can specify the font that is displayed in the Text Object. Be sure that the font is available on the system, especially if the Python script is copied to another system.
The syntax is:
Code:
t1=Text(font="karumbi")
You can also set the font size and style:
Code:
t1=Text(font=("karumbi",20,"bold"))
Be aware that if the font size is changed, it also changes the size of the Text Object.
To see the styles, see 'Python 18 - Buttons'.
Foreground Color
As with other widgets, we can set the foreground color, or the text color.
If we wanted the text color purple, we could use:
Code:
t1=Text(fg="purple")
Height
This is the height of the Text Object, in lines, according to the font size.
An example:
Code:
t1=Text(height=5)
There is no defined default. The setting is determined dynamically based on the font and font size used.
Highlight Background
This is the color of the border, if one exists, when the Text Widget loses focus. Let me give a coding example:
Code:
from tkinter import *
root = Tk()
root.title('Highlight Background Text Object')
root.geometry("900x700")
for i in range(0,9):
root.grid_rowconfigure(i, weight=1)
root.grid_columnconfigure(i, weight=1)
t1=Text(highlightbackground="blue", height=5)
t1.grid(column=0, row=0)
e1=Entry()
e1.grid(column=0, row=3)
root.mainloop()
Here, if you click on the Entry Object at the bottom, you can see that the border of the Text Object becomes blue. When you click back on the Text Object, and give it focus, the border color changes back to black.
Highlight Color
Here, we can set the border color when the object has the focus.
So, we can set both 'highlightcolor' and 'highlightbackground' at the same time:
Code:
t1=Text(highlightbackground="blue",highlightcolor="purple")
It is more noticeable if the width is more than the default of 2 pixels, but the 'bd' parameter has no effect on the highlight. To change the thickness of the highlight, use 'highlightthickness'.
Highlight Thickness
Here, we can set the thickness of the highlighted line around the Text Object. The default width is 1 pixel.
If you do not want any highlighted area, then set the value equal to 0.
To make it a little bigger than the default:
Code:
t1=Text(highlightthickness=3)
Insert Background
This parameter lets you set the background color of the insertion cursor. The default is black.
Once you click on the Text Widget, a blinking cursor appears. Usually, it is black. You can change the color, for instance, to blue:
Code:
t1=Text(insertbackground="blue")
You can change the blinking cursor to be whatever color you wish. Be careful not to make it too similar to the background or it will seem it does not exist.
Insert Border Width
This is the border width around the insertion cursor. By default, it is set to 0.
We can show an example of changing the insertion cursor to blue and a border width of 2 pixels:
Code:
t1=Text(insertbackground="blue", insertborderwidth=2)
Insert Off Time
This is the number of milliseconds that the blinking insertion cursor is off. The default value is 300 milliseconds. Keep in mind that the default time that the cursor is on is set to 600 milliseconds.
Setting the parameter to zero will cause the insertion cursor to not blink.
Code:
t1=Text(insertofftime=600)
Be careful not to have the cursor 'off' for a lengthy amount of time, or it will seem as the cursor disappeared.
Insert On Time
Just like 'insertofftime', this option controls the cursor blink time. The amount is in milliseconds and specifies how long the insertion cursor is visible before it turns off. The default is 600 milliseconds.
Code:
t1=Text(insertontime=700)
You can also set this option to zero, but the cursor will not blink at all or be visible.
Insert Width
The 'insertwidth' is the actual width of the insertion cursor itself. The default is 2 pixels, while the height is the tallest item in the line.
If you change the font size, then the insertion cursor will change as well.
Code:
t1=Text(insertwidth=4)
This works well, but when the insertion cursor is at the leftmost position, the width looks like the default until you move it to the right.
Padx
You can add padding to add an area, or margin, to the left and right of the text area. The default is one pixel.
Code:
t1=Text(padx=5)
Even with padding, the insertion cursor appears as one pixel when at the leftmost position.
The padding helps make the text not appear to be crushed up against the Text Widget border.
Pady
It is possible to add padding at the top and bottom of the text within the Text Widget. The default is one pixel, and if you increase it, there will be more space between the border and the text.
Code:
t1=Text(pady=5)
Using padding can help make the Text Object more visually pleasing by not looking like the text is close to the edge.
Relief
There are six different border styles that can be used. The default is 'SUNKEN', but you can see the various reliefs available in Figure 3 of the 'Python 17 - Labels'.
Code:
t1=Text(relief="raised")
Look at the picture to see the difference between the various types.
Select Background
When you select text, you can specify the color of the selected background. The default is usually light gray.
You can use any of the available colors; just try a color to make sure it is still readable when selected. An example is to make the selected background 'red':
Code:
t1=Text(selectbackground="red")
Select Border Width
Selected text has a border around it. You can specify the width of the selected text border.
With a border of 4, as shown in the example and followed by Figure 2:
Code:
t1=Text(selectborderwidth=4)
FIGURE 2
The default border size of selected text is two pixels.
Spacing1
This is the spacing, measured in pixels, that is added before each paragraph. If a line wraps, then it is still the same paragraph and no extra spacing is placed above the line. The default is 0.
Code:
t1=Text(spacing1=3)
The example would place 3 pixels above each paragraph.
Spacing2
Unlike 'spacing1', the option for 'spacing2' places a vertical space between lines that wrap. The measurement is in pixels. The default is 0, so there is no vertical spacing placed between lines of the same paragraph, except going to the next line.
Code:
t1=Text(spacing2=3)
The example would place 3 pixels above each line within the same paragraph that wraps to the next line.
Spacing3
This option sets the spacing that is placed after the last line of a paragraph. The spacing is used even if the line does not wrap.
You can use this method to space out the lines a little so they do not look so scrunched up.
The default spacing for 'spacing3' is 0.
Code:
t1=Text(spacing3=5)
The example places a space of 5 pixels between each line of text in the Text Object.
State
If you want the Text Widget to support events from the keyboard and mouse, then you need to set this option to 'NORMAL'.
If you do not want any events to be performed on the object, then:
Code:
t1=Text(state=DISABLED)
This basically means that the Text Object is disabled and you cannot enter text or perform any operations on the object. You can still select text with the mouse, but for all purposes, the text is read-only.
Tabs
The option lets you set how a tab controls text. When the tab key is pressed, it advances one character.
You can specify the distance that a tab moves. The measurements are:
- (none) - pixels
- c - centimeters
- i - inches
- m - millimeters
- p - printer's points (1/72 of an inch)
Code:
t1=Text(tabs='1i')
Width
The width of the Text Object in characters. The size will be reflected in the font and font size. If you enlarge the font size, then the Text Widget will change in size as well.
Keep in mind that this is in characters, like the option 'height'. The two options used together will help set a size for your Text Widget.
There is no defined default. The setting is determined dynamically based on the font and font size used.
Wrap
We have used the word 'wrap' previously. There are three choices about how to handle the placement of letters and words when a line is too long for the width of the Text Object. The settings are:
- WORD
- CHAR
- "none"
Choosing 'CHAR' will cause the line to be filled to the end, and the next character that will not fit is placed on the next line. This can cause words to be broken up between lines.
By default, the option is set to 'CHAR'.
Code:
t1=Text(wrap="WORD")
As you can see in Figure 3, the top Text Widget is wrapped by word and the lower Text Object is wrapped by character.
FIGURE 3
By setting 'wrap' to "none", the text will not wrap at all, but be on one line and go out of the Text Object. To view it, you would need to use the keyboard arrow keys after selecting an insertion point, or select text with the mouse and let is scroll the text.
X Scroll Command
When the text goes out of the screen, we are left with few choices to see the text that is not visible. With the 'xscrollcommand', we can have a scrollbar to move the visible text horizontally.
I know that we have not covered using scroll bars yet, but this will be a crash course into some basics of scroll bars.
Code:
from tkinter import *
root = Tk()
root.title("XScrollCommand Example")
root.geometry("500x500")
for i in range(0,9):
root.grid_rowconfigure(i, weight=1)
root.grid_columnconfigure(i, weight=1)
t1=Text(wrap="none", width=10, height=5)
t1.grid(column = 0, row = 0, sticky = 'nwes')
xscrollbar=Scrollbar(orient='horizontal',command=t1.xview)
xscrollbar.grid(column =0,row=1,sticky='we')
t1.config(xscrollcommand=xscrollbar.set)
text = "The quick brown fox jumps over the lazy dog."
t1.insert(END, text)
root.mainloop()
Here, there should be three lines that may look unfamiliar. These three lines are:
Code:
xscrollbar=Scrollbar(orient='horizontal',command=t1.xview)
xscrollbar.grid(column =0,row=1,sticky='we')
t1.config(xscrollcommand=xscrollbar.set)
The first line sets up a vertical scrollbar named 'xscrollbar'. When activated, the command 't1.xview' is executed. This will change the view of the Text Box (T1) horizontally.
The second line is just placing the vertical scrollbar onto the window.
Finally, the last line is used to set the view when the scrollbar is moved to match the movement of the scrollbar.
Y Scroll Command
This option is like the 'xscrollcommand', but vertically managed.
After the last example, I will show an example of a vertical scrollbar:
Code:
from tkinter import *
root=Tk()
root.title("YScrollCommand Example")
root.geometry("500x500")
for i in range(0,9):
root.grid_rowconfigure(i, weight=1)
root.grid_columnconfigure(i, weight=1)
t1=Text(wrap=WORD, width=7, height=3)
t1.grid(column = 0, row = 0, sticky = 'nwes')
yscrollbar=Scrollbar( orient = 'vertical', command = t1.yview)
yscrollbar.grid(column = 1, row = 0, sticky = 'ns')
t1.config(yscrollcommand=yscrollbar.set)
text = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."
t1.insert(END, text)
root.mainloop()
I changed the wrap option to 'WORD' as well as changing the object size. This will force the object to be required to scroll up and down to see all the text. Also, the text being inserted into the Text Object was duplicated for three identical sentences in one paragraph.
Embedding Image
Before we get to the Text Widget Methods, we need to cover one last ability of the Text Object; which is embedding an image into the object.
The following two lines are used to load an image and then place the image into the Text Object:
Code:
image=PhotoImage(file="/home/jarret/Python/tuxsmall.png")
t1.image_create(END, image=image)
The PNG file can be any you have, but keep in mind that it needs to fit into the Text Object. If the image is large, then it may not fit into the Widget properly.
The second line will create the image into the Text Object (t1) and place it at the end of the text. You can place more text after the image if needed.
Be sure to test the image to verify it loads as well as fits in the object.
Conclusion
This covers the use of the standard options for the Text Widget for Tkinter.
I hope you find these options usable, but be sure to check out the next part for covering Methods, Tags and Marks.

