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 code 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")
它是用于这些目的的正确小部件。基本概念是,将属性分配给标记,并将标记应用于小部件中的文本范围。您可以使用文本小部件的
search
命令查找与模式匹配的字符串,这将返回足够的信息,并将标记应用于匹配的范围有关如何将标记应用于文本的示例,请参见我对问题Advanced Tkinter text box?的回答。这并不完全是你想要做的,但它展示了基本的概念
下面是一个示例,说明如何扩展Text类以包含一个方法,用于高亮显示与模式匹配的文本
在这段代码中,模式必须是字符串,不能是已编译的正则表达式。此外,模式必须遵循Tcl's syntax rules for regular expressions
您正在使用tkinter.ttk吗?如果是这样,请先导入tkinter.ttk,然后在导入语句列表中导入tkinter。这对我很管用Here's a picture
相关问题 更多 >
编程相关推荐