There are some methods created for you to achieve this.
I suggest read the Tk documentation (Text, Text.search(), Tags, Indexes)!
Tk provide the text.search method for you so you don't need to implement your own.
Tk Text widget provide you tags which you can create and modify tags.
Workflow:
1. search for a pattern with the text.search() method
that will return an index of the beginning position
2. create a tag with the text.tag_config()
3. add the created tag with the text.tag_add()
from tkinter import Tk, Entry, Button, Text, IntVar
from tkinter import font
class Text_tag_example():
def __init__(self, master):
self.master = master
self.my_font = font.Font(family="Helvetica",size=18)
self.startindex = "1.0" #needed for search method, index ("line, column")
self.endindex = "end" #needed for search method, index (end of index)
self.init_widgets()
def init_widgets(self):
self.txt_widget = Text(self.master, font=self.my_font,
height=10, width=40)
self.txt_widget.grid(row=0, columnspan=2)
self.ent_string = Entry(self.master, font=self.my_font)
self.ent_string.grid(row=1, column=0)
self.but_search = Button(self.master, text="Search", font=self.my_font,
command=self.search_word)
self.but_search.grid(row=1, column=1)
def search_word(self):
word = self.ent_string.get() #get string from entry
countVar = IntVar() # contain the number of chars that matched
searched_position = self.txt_widget.search(pattern=word, index=self.startindex,
stopindex=self.endindex, count=countVar)
self.txt_widget.tag_config("a", foreground="blue", underline=1)
endindex = "{}+{}c".format(searched_position, countVar.get()) #add index+length of word/pattern
self.txt_widget.tag_add("a", searched_position, endindex)
if __name__ == "__main__":
root = Tk()
app = Text_tag_example(root)
root.mainloop()
Usage:
-type in text widget "hello hi bye"
-type in entry widget "hi"
-press Search button
-"hi" should be blue and underlined
Probably your next question will be "How to tag all the same words in text?"
Again read the documentation otherwise you will not be able to understand it!