说明Tkinter文本搜索方法 [英] Explain Tkinter text search method

查看:767
本文介绍了说明Tkinter文本搜索方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't quite understand how text.search method works. For example there is a sentence: Today a red car appeared in the park. I need to find a red car sequence and highlight it. It is found but here is how my highlighting looks like:

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

I am using self.text.search(word, start, stopindex=END) on the sentence. And it looks like search method works exactly like python's regexp search. Adding exact=True didn't change anything since it is default behavior which is why I don't understand what exact=True actually means. How to make a red car highlighted correctly?

推荐答案

search方法返回在起始索引处或之后的第一个匹配项的索引,以及可选的匹配字符数.您有责任通过使用此信息突出显示所发现的内容.

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.

例如,考虑以下搜索:

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

如果找到匹配项,pos将包含该匹配项的第一个字符的索引,而countVar将包含匹配的字符数.您可以使用以下信息来突出显示匹配项,即使用形式为"index + N个字符"或简称为"index + Nc"的索引.例如,如果pos是2.6并且count是9,则匹配的最后一个字符的索引将是2.6+9c

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

这样,并假设您已经配置了一个名为搜索"的标签(例如:text.tag_configure("search", background="green")),则可以将该标签添加到比赛的开头和结尾,如下所示:

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.

这篇关于说明Tkinter文本搜索方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆