10

我不太明白 text.search 方法是如何工作的。例如有一句话:Today a red car appeared in the park.我需要找到a red car序列并突出显示它。找到了,但这是我的突出显示的样子:

在此处输入图像描述

在此处输入图像描述

self.text.search(word, start, stopindex=END)在句子上使用。看起来搜索方法的工作方式与 python 的正则表达式搜索完全一样。添加exact=True并没有改变任何东西,因为它是默认行为,这就是为什么我不明白 exact=True 的实际含义。如何a red car正确突出显示?

4

2 回答 2

15

The search method returns the index of the first match at or after the starting index, and optionally the number of characters that matched. You are responsible for highlighting what it found by 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 character of the match and countVar will contain the number of characters that matched. You can use this information to highlight the match by using an index of the form "index + N chars" or the shorthand "index + Nc". For example, if pos was 2.6 and count was 9, the index of the last character of the match would be 2.6+9c

With that, and assuming you've already configured a tag named "search" (eg: text.tag_configure("search", background="green")), you can add this tag to the start and end of the match like this:

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 to be one character past the end of the previous match.

于 2013-10-19T13:49:55.350 回答
2

可能是索引的问题。

在我的一个程序中,我必须搜索开始索引并计算结束索引

例如我的方法,它工作正常:

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')
于 2013-10-19T13:33:53.143 回答