如何突出显示tkinter.Text中的特定单词?

时间:2020-06-21 04:38:11

标签: python python-3.x tkinter

这不是此问题的副本: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”也会变色。)谁能为我修改此代码,所以它只会使单词变色。

1 个答案:

答案 0 :(得分:0)

所以我发现了这篇文章:Search for whole words in the Text widget with the search method,并且这段代码似乎可以正常工作:

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