关于 Tcl 正则表达式的详细信息可以找到here。特别是,
\y
仅匹配单词的开头或结尾
因此在.highlight_pattern() 中使用模式r'\yor\y' 只会突出显示单词“或”而不是子字符串。
其次,可以使用正则表达式r'"[^"]+"' 来查找引号之间的文本。 [^"] 表示除引号之外的任何字符。如果您不想突出显示引号,则需要将标签从匹配开始后的一个字符添加到匹配结束前的一个字符。但是,使用这种模式,包含换行符的引用文本将不会被突出显示。如果您还想突出显示包含换行符的引用文本,可以使用正则表达式r'"([^"]|\n)+"'。
这是一个基于How to highlight text in a tkinter Text widget的回答的例子
import tkinter as tk
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.
'''
self.tag_remove(tag, start, end) # remove tag first
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")
def highlight_quoted_text(self, tag, start="1.0", end="end"):
self.tag_remove(tag, start, end) # remove tag first
start = self.index(start)
end = self.index(end)
count = tk.IntVar()
while True:
index = self.search(r'"[^"]+"', start, end,
count=count, regexp=True)
if index == "":
break
start = self.index("%s+%sc" % (index, count.get()))
self.tag_add(tag, "%s+1c" % index, "%s-1c" % start)
root = tk.Tk()
text = CustomText(root)
text.tag_configure('highlight', background='yellow')
text.tag_configure('quoted', background='orange')
text.pack()
text.insert('1.0', "We can go for the southern port or the northern port.\n\"Text surronded by quotes\" and regular text without quotes and \"quoted text again\"")
tk.Button(root, text='Highlight "or"', command=lambda: text.highlight_pattern(r'\yor\y', 'highlight', regexp=True)).pack()
tk.Button(root, text='Highlight quoted', command=lambda: text.highlight_quoted_text('quoted')).pack()
root.mainloop()