如何在 tkinter 文本小部件中突出显示文本

2025-01-14 08:50:00
admin
原创
142
摘要:问题描述:我想知道如何根据某些模式改变某些单词和表达的风格。我正在使用Tkinter.Text小部件,但我不知道如何做这样的事情(与文本编辑器中的语法突出显示相同)。我甚至不确定这是否是用于此目的的正确小部件。解决方案 1:它是用于这些目的的正确小部件。基本概念是,您为标签分配属性,并将标签应用于小部件中的文...

问题描述:

我想知道如何根据某些模式改变某些单词和表达的风格。

我正在使用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()
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3958  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2737  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   74  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   83  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   70  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用