Explain Tkinter Text Search Method

I do not quite understand how the text.search method works. For example, there is a sentence: Today a red car appeared in the park. I need to find the sequence of a red car and select it. It is found, but here is what my highlight looks like:

enter image description here

enter image description here

I use self.text.search(word, start, stopindex=END) in a sentence. And it looks like the search method works exactly the same as python regexp search. Adding exact=True did not change anything, as this is the default behavior, so I don’t understand what exactly = True actually means. How to make a red car highlighted correctly?

+7
source share
2 answers

The search method returns the index of the first match in or after the start index and, if necessary, the number of matches of characters. You are responsible for highlighting what was found using this information.

For example, consider this search:

 countVar = tk.StringVar() pos = text.search("a red car", "1.0", stopindex="end", count=countVar) 

If a match is found, pos will contain the index of the first match character, and countVar will contain the number of matching characters. You can use this information to highlight a match using an index of the form "index + N chars" or the abbreviation "index + Nc". For example, if pos were 2.6 and count was 9, the index of the last match would be 2.6+9c

After that, and provided that you have already set up a tag with the name "search" (for example, text.tag_configure("search", background="green") ), you can add this tag to the beginning and end of the match as follows:

 text.tag_add("search", pos, "%s + %sc" (pos, countVar.get())) 

To highlight all matches, just put the search command in a loop and adjust the starting position one character after the end of the previous match.

+10
source

This may be an index issue.

In my program, I need to find the start index and calculate the end index

My method, for example, works fine:

 def highlight(self): start = 1.0 pos = self.area_example.search(self.item.name, start, stopindex=END) while pos: length = len(self.item.name) row, col = pos.split('.') end = int(col) + length end = row + '.' + str(end) self.area_example.tag_add('highlight', pos, end) start = end pos = self.area_example.search(self.item.name, start, stopindex=END) self.area_example.tag_config('highlight', background='white', foreground='red') 
0
source

Source: https://habr.com/ru/post/956311/


All Articles