这是用于这些目的的正确小部件。基本概念是,将属性分配给标签,然后将标签应用于小部件中的文本范围。您可以使用文本小部件的
search命令来查找与您的模式匹配的字符串,这将为您返回足够的信息,将标记应用于匹配的范围。
以下是如何扩展Text类以包括突出显示与模式匹配的文本的方法的示例。
在此代码中,模式必须是字符串,不能是已编译的正则表达式。另外,该模式必须遵守Tcl的正则表达式语法规则。
class CustomText(tk.Text): '''A text widget with a new method, highlight_pattern() example: text = CustomText() text.tag_configure("red", foreground="#ff0000") text.highlight_pattern("this should be red", "red") The highlight_pattern method is a simplified python version of the tcl pre at http://wiki.tcl.tk/3246 ''' def __init__(self, *args, **kwargs): tk.Text.__init__(self, *args, **kwargs) def highlight_pattern(self, pattern, tag, start="1.0", end="end", regexp=False): '''Apply the given tag to all text that matches the given pattern If 'regexp' is set to True, pattern will be treated as a regular expression according to Tcl's regular expression syntax. ''' start = self.index(start) end = self.index(end) self.mark_set("matchStart", start) self.mark_set("matchEnd", start) self.mark_set("searchLimit", end) count = tk.IntVar() while True: index = self.search(pattern, "matchEnd","searchLimit", count=count, regexp=regexp) if index == "": break if count.get() == 0: break # degenerate pattern which matches zero-length strings self.mark_set("matchStart", index) self.mark_set("matchEnd", "%s+%sc" % (index, count.get())) self.tag_add(tag, "matchStart", "matchEnd")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)