首页 > 解决方案 > 如何突出显示 tkinter.Text 中的特定单词?

问题描述

这不是这个问题的副本:How to highlight text in a tkinter Text widget。这更像是一个延续。从这个问题,我得到了这个代码:

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")

此代码运行良好,但我遇到了问题。我实际上想在我的 python 编辑器的颜色编码中使用这个突出显示功能。问题是,每当我使用它时,我都需要它来为单词着色,但它会在找到它的任何地方为字母着色,即使换句话说。(例如:当我尝试突出显示单词“on”时,单词“one”中的“on”也会着色)任何人都可以为我修改此代码,所以它只会着色单词。

标签: pythonpython-3.xtkinter

解决方案


所以我找到了这篇文章:使用搜索方法在文本小部件中搜索整个单词,这段代码似乎运行良好:

textArea.highlight_pattern("\\y" + word + "\\y", "tag", regexp=True)

推荐阅读