如何在tkinter Text小部件中高亮文本

19 投票
2 回答
39508 浏览
提问于 2025-04-16 04:31

我想知道怎么根据特定的模式来改变某些词和表达的样式。

我正在使用 Tkinter.Text 这个组件,但我不太确定怎么做到这一点(就像文本编辑器里的语法高亮那样)。我甚至不确定这个组件是否适合用来做这个。

2 个回答

1

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')]

现在这些值可以用来在文本小部件中高亮显示模式。

参考资料

CustomText 小部件

这是一个 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"\bhello\b")
    text.highlight_pattern(r"\bworld\b", "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()
50

这个小部件非常适合用来做这些事情。基本的概念是,你给标签设置属性,然后把这些标签应用到小部件中的一段文本上。你可以使用文本小部件的 search 命令来查找符合你模式的字符串,这样就能得到足够的信息来把标签应用到匹配的文本范围上。

如果你想看看如何给文本应用标签,可以参考我对这个问题的回答:Advanced Tkinter text box?。虽然这不是你想做的完全一样,但它展示了基本的概念。

接下来是一个例子,展示了如何扩展 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")

撰写回答