Tkinter Text Find Text
You can use the search( ) method within the Text control to find the specified string. This method will pass back the index position of the first specified string found. Assuming the object of the Text control is text, its syntax is as follows.
pos=text.search(key, startindex, endindex)
(1) pos: pass back the index position of the found string, or pass back the empty string if the search fails.
(2) key: the string to be searched.
(3) startindex: the starting position of the search.
(4) endindex: find the end position, if the search to the end of the document can use END.
Example#1
For the Find Text application, the text found will be displayed with a yellow background.
from tkinter import *
def mySearch():
text.tag_remove("found","1.0",END)
start = "1.0"
key = entry.get()
if (len(key.strip()) == 0):
return
while True:
pos = text.search(key,start,END)
# print("pos= ",pos) # pos= 3.0 pos= 4.0 pos=
if (pos == ""):
break
text.tag_add("found",pos,"%s+%dc" %(pos,len(key)))
start = "%s+%dc" % (pos,len(key))
# print("start= ",start) # start= 3.0+3c start= 4.0+3c
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
root.rowconfigure(1,weight=1)
root.columnconfigure(0,weight=1)
entry = Entry()
entry.grid(row=0,column=0,padx=5,sticky=W+E)
btn = Button(root,text="Find",command=mySearch)
btn.grid(row=0,column=1,padx=5,pady=5)
# Create Text
text = Text(root,undo=True)
text.grid(row=1,column=0,columnspan=2,padx=3,
pady=5,sticky=N+S+W+E)
text.insert(END,"Five Hundred Miles\n") # Set Tag at the same time when inserting
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.insert(END,"A hundred miles,\n")
text.tag_configure("found", background="yellow")
root.mainloop()
Output:
The first procedural code that will be unfamiliar to the reader is line 12.
pos = text.search(key,start,END)
The second piece of code that is unfamiliar to the reader is lines 15 and 16, as shown below.
text.tag_add("found",pos,"%s+%dc" %(pos,len(key)))
start = "%s+%dc" % (pos,len(key))
The above line 15 pos is the starting position of the joined label and the ending position of the label is an indexed expression.
"%s+%dc" % (pos,len(key))
The above is the end index position of the found string, which is equivalent to the pos position plus the length of the key keyword. Line 16 of the program updates the start position of the search to prepare for the next search.