如何在 tkinter 文本小部件中突出显示文本
- 2025-01-14 08:50:00
- admin 原创
- 142
问题描述:
我想知道如何根据某些模式改变某些单词和表达的风格。
我正在使用Tkinter.Text
小部件,但我不知道如何做这样的事情(与文本编辑器中的语法突出显示相同)。我甚至不确定这是否是用于此目的的正确小部件。
解决方案 1:
它是用于这些目的的正确小部件。基本概念是,您为标签分配属性,并将标签应用于小部件中的文本范围。您可以使用文本小部件的search
命令来查找与您的模式匹配的字符串,这将返回足够的信息,将标签应用于匹配的范围。
有关如何将标签应用于文本的示例,请参阅我对问题“高级 Tkinter 文本框?”的回答。这不完全是您想要做的,但它展示了基本概念。
下面是一个示例,说明如何扩展 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 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")
解决方案 2:
Bryan Oakley 的回答对我在许多文本小部件上配置高亮有很大帮助。多亏了他们,我现在能够理解高亮的工作原理了。
缺点
我发现的唯一缺点是 tcl/tk 使用的正则表达式语法与 python 正则表达式语法之间的差异。tcl/tk 正则表达式语法接近正常的 python 正则表达式语法,但并不相同。由于这个问题,许多可用的正则表达式测试应用程序无法用于为 tkinter 搜索方法编写正则表达式。
解决方案
注意:如果文本小部件有嵌入的图像或小部件,则这将无法按预期工作,因为小部件中的索引与文本部分的索引不同。
我尝试将 python 的正则表达式标准库与 tkinter Text 小部件结合起来。
import re
import tkinter as tk
...
def search_re(self, pattern):
"""
Uses the python re library to match patterns.
pattern - the pattern to match.
"""
matches = []
text = textwidget.get("1.0", tk.END).splitlines()
for i, line in enumerate(text):
for match in re.finditer(pattern, line):
matches.append((f"{i + 1}.{match.start()}", f"{i + 1}.{match.end()}"))
return matches
返回值是包含匹配项的起始和终止索引的元组列表。示例:
[('1.1', '1.5'), ('1.6', '1.10'), ('3.1', '3.5')]
现在这些值可用于突出显示文本小部件中的模式。
参考
re.finditer
自定义文本小部件
这是 tkinter 的 Text 小部件的包装器,带有使用正则表达式库突出显示和搜索的附加方法。它基于 bryan 的代码,感谢他们。
import re
import tkinter as tk
class CustomText(tk.Text):
"""
Wrapper for the tkinter.Text widget with additional methods for
highlighting and matching regular expressions.
highlight_all(pattern, tag) - Highlights all matches of the pattern.
highlight_pattern(pattern, tag) - Cleans all highlights and highlights all matches of the pattern.
clean_highlights(tag) - Removes all highlights of the given tag.
search_re(pattern) - Uses the python re library to match patterns.
"""
def __init__(self, master, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.master = master
# sample tag
self.tag_config("match", foreground="red")
def highlight(self, tag, start, end):
self.tag_add(tag, start, end)
def highlight_all(self, pattern, tag):
for match in self.search_re(pattern):
self.highlight(tag, match[0], match[1])
def clean_highlights(self, tag):
self.tag_remove(tag, "1.0", tk.END)
def search_re(self, pattern):
"""
Uses the python re library to match patterns.
Arguments:
pattern - The pattern to match.
Return value:
A list of tuples containing the start and end indices of the matches.
e.g. [("0.4", "5.9"]
"""
matches = []
text = self.get("1.0", tk.END).splitlines()
for i, line in enumerate(text):
for match in re.finditer(pattern, line):
matches.append((f"{i + 1}.{match.start()}", f"{i + 1}.{match.end()}"))
return matches
def highlight_pattern(self, pattern, tag="match"):
"""
Cleans all highlights and highlights all matches of the pattern.
Arguments:
pattern - The pattern to match.
tag - The tag to use for the highlights.
"""
self.clean_highlights(tag)
self.highlight_all(pattern, tag)
示例用法
下面的代码使用了上述类,并展示了如何使用它的示例:
import tkinter as tk
root = tk.Tk()
# Example usage
def highlight_text(args):
text.highlight_pattern(r"hello")
text.highlight_pattern(r"world", "match2")
text = CustomText(root)
text.pack()
text.tag_config("match2", foreground="green")
# This is not the best way, but it works.
# instead, see: https://stackoverflow.com/a/40618152/14507110
text.bind("<KeyRelease>", highlight_text)
root.mainloop()
扫码咨询,免费领取项目管理大礼包!