解释 Tkinter 文本搜索方法 [英] Explain Tkinter text search method

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

问题描述

我不太明白 text.search 方法是如何工作的.例如有一句话:今天公园里出现一辆红色汽车.我需要找到一辆红色汽车序列并突出显示它.找到了,但这里是我的突出显示的样子:

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 的正则表达式搜索完全一样.添加 exact=True 没有改变任何东西,因为它是默认行为,这就是为什么我不明白确切=True 的实际含义.如何让一辆红色的车正确高亮?

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?

推荐答案

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

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 将包含匹配的字符数.您可以使用此信息通过使用索引 + N 个字符"形式的索引或简写索引 + 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

有了这个,假设你已经配置了一个名为search"的标签(例如: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天全站免登陆