Now that we've covered the primary commands, we can start on the Methods, Tags and Marks.
If you intend on using a Text Widget, or multiples, these are very handy abilities other than the standard options.
Methods
Now, we can move on to doing something with text in the Text Object. Let's start with the five methods:
We can insert text into the Text Object by specifying the line, character place and the text. The entry is coded as:
You should notice that at the end of the string text is a newline (\n) character. Keep this in mind.
This works well to place on the first line, but if you want to place something else on line 5, there is no line 5 yet. There are only line 1 and 2 because of the newline.
We can initialize a Text Object with a specified number of lines:
Here, we set up 20 blank lines. Now we can specify any line number between 1 and 20 to place text. As long as you place text one line at a time, using a newline character, you can then place text on the next line.
Keep in mind that the second value after the period is used for the character placement within the line.
For example, if you want to place text on line 1 at position 10, the code would be:
If the line does not contain at least 10 characters, then it will be placed at the end of the existing text. If there are over 10 characters on line 1, then the text is inserted in the middle of the existing text.
Delete Method
We can delete characters, even just a single one, from the Text Object. To do this, we need to know the spot, or index, of placing the first character to delete. If there is more than one character to delete from the Text Object, then we need to specify the ending index.
Let's assume we have an existing string on line 1 and insert text into the 10th place. We can then remove it as long as we know how many characters it is in length. Let's assume the length of the text to remove is 8 characters:
If you want to delete an entire line, such as line 1:
Here, there is a constant used as 'end' for the end of the line. Keep in mind that line 1 will be blank, while other lines remain in their original position.
Another constant is 'tk.ALL', for all lines and characters, or even 'tk.END', for the current position to the end of the Text Object.
With the examples I have used, these constants will not work, since I do not define 'tk', but define 'Tk'. To make this work, you need to define both at the beginning of the code:
A good example of Insert is in the Get Method example.
Get Method
If you want to get the data entered into a Text Object, you can use the Get Method.
There are two parameters that we can use this:
Let's make an example that has a Text Object and after entering the data, we can copy the data into a variable and then place it into a second Text Object.
You may notice that the Text Object is a single row that has a larger weight value. The 'OK' button is placed on Row 0 and it is centered vertically against the Text Object.
After pressing the button, all the contents of the Text Object (t1) is placed into the variable 'data1' using the 'Get Method'. A new Text Object (t2) is created, and the data is copied from the variable into the new Text Object using the 'Insert Method'.
Index Method
The Index Method is like a Find function, except you aren't searching for a string. You are searching for a specific point in the text. The values are as follows:
See Method
You can use this method to see a string that is not visible.
This works both horizontally and vertically.
In the following code, there are two text boxes, each of which has four buttons. The top Text Object comprises multiple lines. The lower Text Widget is all on one line, but part of it is not visible.
With the top Text Widget, the four buttons move to a different line of the text and show it in the box. The Text Object only displays one line at a time, but there aren't any scroll bars. When a button is pressed, it calls a command. The command uses the 'set' method to change the position based on 'line.character'.
The lower object works the same way, but moves across the text horizontally and not vertically.
The code is:
It is a very basic example, but you should be able to notice how the 'see' method works.
Tags
Tags are a way to set up a style sheet, so to speak, similar to in an EPUB file. You can set a name, or tag, to represent specific formatting. You can then apply the tag, it’s formatting to text within the Text Widget.
There are five different tagging methods:
The first thing we need to do is add a tag that we can use later. The method will be attached to a Text Widget, which in our examples is called 't1'.
We use the Text Widget name (t1) with the 'tag_add' method. Within parentheses, we need to specify the tag name and the start and stop of the text to place the tag on:
The tag we are assigning, or adding, is named 'title'. The tag covers Line 1 starting at character 0 and going to the end of the line.
Tag_Configure
Once the tag is added to specific text, we need to configure the way the text will be changed. Here, the tag name is still 'title' and uses a specific font of DejaVu Sans, font size of 20 and will be bold.
When we configured the 'title' tag, we specified how it would affect the text, but when we add the tag, we specify what text is being changed.
Tag_Bind
After we configure a tag, we can bind it to a specific keypress or mouse button.
Let's assume we are going to create a 'link' in a text that when clicked will open a website.
First, we need to include an import of a module called 'webbrowser' so we can handle the 'link'. Any calls to the module will be managed by the system's default web browser.
Next, we need to add the specific tag to the text.
Here, the tag name is 'link_tag'. It is changing the text on line 3 from character 6 to 10.
How it is being changed is as follows from the 'configure' method:
The text is changed to being blue and underlined.
Now, we need to bind the tag to an event; in this case it is '<Button-1>', or a right-click. The code is:
When clicked with 'Button-1', it creates a variable named 'url' that contains the link to Linux.org. After it creates the variable, it calls 'webbrowser.open' method and passes the 'url' variable to it. This should open the default browser at the given URL.
The following is a more detailed example:
Tag_Remove
When removing a tag, you 'unattach' the tag from specified text. Once this is removed, you cannot reapply it without adding it back to the required text.
So, from the above example, I can remove the 'purple_text_tag' added to Line 2 with:
If you want to make this line purple again, you only need to use the 'tag_add' command again for the line and then apply the 'tag_configure'.
Tag_Delete
If you use the 'tag_delete' method, you will remove the tag from a specified area of text, and delete the tag name so it cannot be added again, unlike with 'tag_remove'.
If you delete the tag without specifying the text it affects, then the change is not made to the text, but the tag is gone.
You can remove and delete the tag with:
If you try to use 'purple_text_tag' with a 'tag_add' statement, then nothing will occur since the 'purple_text_tag' is not defined.
Marks
Within the Text Widget, we can place anchors, called marks, to allow the spot to be recognized by a name.
You can retrieve the mark locations for use by tags and other code you may write that requires a specific location of text. Keep in mind that the anchor is not set and can 'float'. If text is moved, the anchor is attached to a character.
There are five commands for using marks:
Using the 'mark_set' command, we can create a mark by giving it a name and a location.
For example:
With this command, we set a mark at this location, called 'author'. Now, if I add a button to the window, I can click the button to move the insertion cursor to the mark. But to make this work, we also need to change the focus to the Text Object (t1). The code is:
There is also a label (l1) that displays the mark location when the button is pressed.
The function for the button press does:
Mark_Unset
After a mark is added, you can remove the mark by using the unset command and passing the mark name that you want to remove.
If the text around a mark is deleted, the mark remains unless you unset it.
You cannot unset a constant mark, such as 'insert' and 'current'.
Index(mark)
Here, we can return the location of the mark.
This command is covered in the previous example, and you can place the value into a variable.
You can also use 'insert' or 'current' to get the insertion cursor placement, or the place closest to the mouse cursor.
Mark_Names
There is a command to get a list, in a tuple, of all the available marks for the given widget. Of course, the list includes 'current' and 'insert' as well as those made by the coder.
In the previous example, I can place the following line at the end of the button press, named 'showmark':
The output would be:
Mark_Gravity
If you use the previous example, and press the button, you'll see that the mark is placed at position '5.2'. Now that the insertion cursor is at the mark, press the spacebar twice. Now, click on the button again. The location is now '5.4'. If you press the Enter key and then press the button, the location is now at '6.0'. The mark remains with the character (Y) to its right, by default. If you delete the character (Y), it will now have gravity to the new letter to its right (o).
This is why I described the mark as an anchor that is not set, but floats.
You can set the gravity of the mark by specifying the name of the mark and then setting the gravity to 'LEFT' or 'RIGHT'.
If in the previous example, we change the default gravity to 'LEFT':
Then press the button to see the location; everything is like before. Now, if we add some spaces, add characters or press Enter and then press the button, the insertion cursor moves back to the space after the dash, since this is its anchor character. If we delete the space, then the new anchor character is the dash.
Conclusion
This covers the use of the Methods, Tags and Marks of the Text Widget for Tkinter.
I hope you learned something and can use the information in your programs. Keep in mind that there is still more to come.
If you intend on using a Text Widget, or multiples, these are very handy abilities other than the standard options.
Methods
Now, we can move on to doing something with text in the Text Object. Let's start with the five methods:
- insert
- delete
- get
- index
- see
We can insert text into the Text Object by specifying the line, character place and the text. The entry is coded as:
Code:
t1.insert("1.0","Text to be placed into the text box.\n")
You should notice that at the end of the string text is a newline (\n) character. Keep this in mind.
This works well to place on the first line, but if you want to place something else on line 5, there is no line 5 yet. There are only line 1 and 2 because of the newline.
We can initialize a Text Object with a specified number of lines:
Code:
t1=Text()
t1.grid(column=0, row=0)
for i in range(0,20):
t1.insert(str(i)+".0","\n")
Here, we set up 20 blank lines. Now we can specify any line number between 1 and 20 to place text. As long as you place text one line at a time, using a newline character, you can then place text on the next line.
Keep in mind that the second value after the period is used for the character placement within the line.
For example, if you want to place text on line 1 at position 10, the code would be:
Code:
t1.insert("1.10","New Text")
If the line does not contain at least 10 characters, then it will be placed at the end of the existing text. If there are over 10 characters on line 1, then the text is inserted in the middle of the existing text.
Delete Method
We can delete characters, even just a single one, from the Text Object. To do this, we need to know the spot, or index, of placing the first character to delete. If there is more than one character to delete from the Text Object, then we need to specify the ending index.
Let's assume we have an existing string on line 1 and insert text into the 10th place. We can then remove it as long as we know how many characters it is in length. Let's assume the length of the text to remove is 8 characters:
Code:
t1.delete("1.10","1.18")
If you want to delete an entire line, such as line 1:
Code:
t1.delete("1.0","1.end")
Here, there is a constant used as 'end' for the end of the line. Keep in mind that line 1 will be blank, while other lines remain in their original position.
Another constant is 'tk.ALL', for all lines and characters, or even 'tk.END', for the current position to the end of the Text Object.
With the examples I have used, these constants will not work, since I do not define 'tk', but define 'Tk'. To make this work, you need to define both at the beginning of the code:
Code:
from tkinter import *
import tkinter as tk
A good example of Insert is in the Get Method example.
Get Method
If you want to get the data entered into a Text Object, you can use the Get Method.
There are two parameters that we can use this:
- starting index
- ending index
Let's make an example that has a Text Object and after entering the data, we can copy the data into a variable and then place it into a second Text Object.
Code:
from tkinter import *
import tkinter as tk
def gettest():
t2=Text()
t2.grid(column=0, row=2)
data1=t1.get("1.0",tk.END)
t2.insert("1.0",data1)
root = Tk()
root.title('Get Text Box')
root.geometry("900x900")
for i in range(0,10):
root.grid_rowconfigure(i, weight=1)
root.grid_columnconfigure(i, weight=1)
t1=Text()
t1.grid(column=0, row=0)
b1=Button(root, text="OK", command=gettest)
b1.grid(column=7, row=0)
root.mainloop()
You may notice that the Text Object is a single row that has a larger weight value. The 'OK' button is placed on Row 0 and it is centered vertically against the Text Object.
After pressing the button, all the contents of the Text Object (t1) is placed into the variable 'data1' using the 'Get Method'. A new Text Object (t2) is created, and the data is copied from the variable into the new Text Object using the 'Insert Method'.
Index Method
The Index Method is like a Find function, except you aren't searching for a string. You are searching for a specific point in the text. The values are as follows:
- "line.end" - a line number and the word 'end' to specify the length of the line
- tk.insert - position of the insert character, the cursor
- tk.CURRENT - position closest to the mouse cursor
- tk.END - the position of the last character in the text
- tk.SEL_FIRST - position before the selected text, if any is selected
- tk.SEL_LAST - position after the selected text, if any is selected
- 'markname' - the position of the marked position (we'll get into this)
- tag.first - position before the tagged position (we'll get into this)
- tag.last - position after the tagged position (we'll get into this)
- @x,y - position closest to the x,y coordinate
See Method
You can use this method to see a string that is not visible.
This works both horizontally and vertically.
In the following code, there are two text boxes, each of which has four buttons. The top Text Object comprises multiple lines. The lower Text Widget is all on one line, but part of it is not visible.
With the top Text Widget, the four buttons move to a different line of the text and show it in the box. The Text Object only displays one line at a time, but there aren't any scroll bars. When a button is pressed, it calls a command. The command uses the 'set' method to change the position based on 'line.character'.
The lower object works the same way, but moves across the text horizontally and not vertically.
The code is:
Code:
from tkinter import *
def Line1():
t1.see("1.0")
def Line2():
t1.see("2.0")
def Line3():
t1.see("3.0")
def End1():
t1.see(END)
def Left():
t2.see("1.0")
def Mid1():
t2.see("1.30")
def Mid2():
t2.see("1.56")
def End2():
t2.see(END)
root = Tk()
root.title("See Method")
root.geometry("900x700")
for i in range(0,9):
root.grid_rowconfigure(i, weight=1)
root.grid_columnconfigure(i, weight=1)
t1=Text(height=1, width=50,wrap=WORD)
t1.grid(column=0, row=0)
t1.insert(END, "The light of a candle\n")
t1.insert(END, "Is transferred to another candle — \n")
t1.insert(END, "spring twilight.\n")
t1.insert(END, " - Yosa Buson")
b1=Button(text="Line 1",command=Line1)
b1.grid(column=1, row=2)
b2=Button(text="Line 2",command=Line2)
b2.grid(column=2, row=2)
b3=Button(text="Line 3",command=Line3)
b3.grid(column=3, row=2)
b4=Button(text="Last Line",command=End1)
b4.grid(column=4, row=2)
t2=Text(height=1, width=20,wrap="none")
t2.grid(column=0, row=3)
t2.insert(END, "The light of a candle Is transferred to another candle — spring twilight. - Yosa Buson")
b5=Button(text="Left Side",command=Left)
b5.grid(column=1, row=4)
b6=Button(text="Mid 1",command=Mid1)
b6.grid(column=2, row=4)
b7=Button(text="Mid 2",command=Mid2)
b7.grid(column=3, row=4)
b8=Button(text="End",command=End2)
b8.grid(column=4, row=4)
root.mainloop()
It is a very basic example, but you should be able to notice how the 'see' method works.
Tags
Tags are a way to set up a style sheet, so to speak, similar to in an EPUB file. You can set a name, or tag, to represent specific formatting. You can then apply the tag, it’s formatting to text within the Text Widget.
There are five different tagging methods:
- tag_add
- tag_config
- tag_bind
- tag_remove
- tag_delete
The first thing we need to do is add a tag that we can use later. The method will be attached to a Text Widget, which in our examples is called 't1'.
We use the Text Widget name (t1) with the 'tag_add' method. Within parentheses, we need to specify the tag name and the start and stop of the text to place the tag on:
Code:
t1.tag_add("title", "1.0", "1.end")
The tag we are assigning, or adding, is named 'title'. The tag covers Line 1 starting at character 0 and going to the end of the line.
Tag_Configure
Once the tag is added to specific text, we need to configure the way the text will be changed. Here, the tag name is still 'title' and uses a specific font of DejaVu Sans, font size of 20 and will be bold.
Code:
t1.tag_configure("title", font=("DejaVu Sans",20,"bold")
When we configured the 'title' tag, we specified how it would affect the text, but when we add the tag, we specify what text is being changed.
Tag_Bind
After we configure a tag, we can bind it to a specific keypress or mouse button.
Let's assume we are going to create a 'link' in a text that when clicked will open a website.
First, we need to include an import of a module called 'webbrowser' so we can handle the 'link'. Any calls to the module will be managed by the system's default web browser.
Next, we need to add the specific tag to the text.
Code:
t1.tag_add("link_tag", "3.6", "3.10")
Here, the tag name is 'link_tag'. It is changing the text on line 3 from character 6 to 10.
How it is being changed is as follows from the 'configure' method:
Code:
t1.tag_configure("link_tag", foreground="blue", underline=True)
The text is changed to being blue and underlined.
Now, we need to bind the tag to an event; in this case it is '<Button-1>', or a right-click. The code is:
Code:
t1.tag_bind("link_tag", "<Button-1>", lambda event, url="http://linux.org": webbrowser.open(url))
When clicked with 'Button-1', it creates a variable named 'url' that contains the link to Linux.org. After it creates the variable, it calls 'webbrowser.open' method and passes the 'url' variable to it. This should open the default browser at the given URL.
The following is a more detailed example:
Code:
from tkinter import *
import webbrowser
def apply_tags(t1):
t1.tag_configure("italics_tag", font=("DejaVu Serif", 15, "bold italic"))
t1.tag_configure("purple_text_tag", foreground="purple")
t1.tag_configure("link_tag", foreground="blue", underline=True)
t1.tag_bind("link_tag", "<Button-1>", lambda event, url="http://linux.org": webbrowser.open(url))
t1.tag_add("italics_tag", "1.0", "1.5")
t1.tag_add("purple_text_tag", "2.0", "2.end")
t1.tag_add("link_tag", "3.6", "3.10")
root = Tk()
root.title("Tag Text Object Example")
root.geometry("900x700")
t1 = Text(root, wrap="word", width=40, height=10)
t1.grid(column=0, row=0)
t1.insert(END, "Hello, Tux!\n")
t1.insert(END, "This text will all be purple.\n")
t1.insert(END, "Click here to open Linux.org.")
apply_tags(t1)
root.mainloop()
Tag_Remove
When removing a tag, you 'unattach' the tag from specified text. Once this is removed, you cannot reapply it without adding it back to the required text.
So, from the above example, I can remove the 'purple_text_tag' added to Line 2 with:
Code:
t1.tag_remove("purple_text_tag","2.0","2.end")
If you want to make this line purple again, you only need to use the 'tag_add' command again for the line and then apply the 'tag_configure'.
Tag_Delete
If you use the 'tag_delete' method, you will remove the tag from a specified area of text, and delete the tag name so it cannot be added again, unlike with 'tag_remove'.
If you delete the tag without specifying the text it affects, then the change is not made to the text, but the tag is gone.
You can remove and delete the tag with:
Code:
t1.tag_delete("purple_text_tag","2.0","2.end")
If you try to use 'purple_text_tag' with a 'tag_add' statement, then nothing will occur since the 'purple_text_tag' is not defined.
Marks
Within the Text Widget, we can place anchors, called marks, to allow the spot to be recognized by a name.
You can retrieve the mark locations for use by tags and other code you may write that requires a specific location of text. Keep in mind that the anchor is not set and can 'float'. If text is moved, the anchor is attached to a character.
There are five commands for using marks:
- mark_set
- mark_unset
- index(mark)
- mark_names
- mark_gravity
Using the 'mark_set' command, we can create a mark by giving it a name and a location.
For example:
Code:
t1.mark_set("author",5.2)
With this command, we set a mark at this location, called 'author'. Now, if I add a button to the window, I can click the button to move the insertion cursor to the mark. But to make this work, we also need to change the focus to the Text Object (t1). The code is:
Code:
from tkinter import *
def showmark():
place = t1.index("author")
l1.configure(text=place)
t1.focus_set()
t1.mark_set("insert",place)
root = Tk()
root.title("Mark_Set Text Object Example")
root.geometry("500x500")
t1 = Text(root, wrap="word", width=40, height=6)
t1.grid(column=0, row=0)
t1.insert(1.0,"The light of a candle\nIs transferred to another candle —\nspring twilight.\n\n- Yosa Buson\n")
t1.mark_set("author",5.2)
l1=Label(text=" - ")
l1.grid(column=0,row=3)
b1=Button(text="Show Mark",command=showmark)
b1.grid(column=0,row=2)
root.mainloop()
There is also a label (l1) that displays the mark location when the button is pressed.
The function for the button press does:
- finds the place of the mark and puts the value in 'place'
- puts the value of 'place' onto the label (l1)
- places the focus on the Text Box (t1)
- performs a mark_set to place the cursor ("insert") at 'place'
Mark_Unset
After a mark is added, you can remove the mark by using the unset command and passing the mark name that you want to remove.
If the text around a mark is deleted, the mark remains unless you unset it.
You cannot unset a constant mark, such as 'insert' and 'current'.
Index(mark)
Here, we can return the location of the mark.
This command is covered in the previous example, and you can place the value into a variable.
You can also use 'insert' or 'current' to get the insertion cursor placement, or the place closest to the mouse cursor.
Mark_Names
There is a command to get a list, in a tuple, of all the available marks for the given widget. Of course, the list includes 'current' and 'insert' as well as those made by the coder.
In the previous example, I can place the following line at the end of the button press, named 'showmark':
Code:
print(f'Mark Names: {t1.mark_names()}')
The output would be:
Code:
Mark Names: ('insert', 'current', 'author')
Mark_Gravity
If you use the previous example, and press the button, you'll see that the mark is placed at position '5.2'. Now that the insertion cursor is at the mark, press the spacebar twice. Now, click on the button again. The location is now '5.4'. If you press the Enter key and then press the button, the location is now at '6.0'. The mark remains with the character (Y) to its right, by default. If you delete the character (Y), it will now have gravity to the new letter to its right (o).
This is why I described the mark as an anchor that is not set, but floats.
You can set the gravity of the mark by specifying the name of the mark and then setting the gravity to 'LEFT' or 'RIGHT'.
If in the previous example, we change the default gravity to 'LEFT':
Code:
t1.mark_gravity("author",LEFT)
Then press the button to see the location; everything is like before. Now, if we add some spaces, add characters or press Enter and then press the button, the insertion cursor moves back to the space after the dash, since this is its anchor character. If we delete the space, then the new anchor character is the dash.
Conclusion
This covers the use of the Methods, Tags and Marks of the Text Widget for Tkinter.
I hope you learned something and can use the information in your programs. Keep in mind that there is still more to come.

