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

Lat*_*ice 13 python text tkinter

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

我正在使用Tkinter.Text小部件,我不知道如何做这样的事情(文本编辑器中语法高亮的相同想法).我不确定即使这是用于此目的的正确小部件.

Bry*_*ley 36

它是用于这些目的的正确小部件.基本概念是,您将属性分配给标记,并将标记应用于窗口小部件中的文本范围.您可以使用文本小部件的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")
Run Code Online (Sandbox Code Playgroud)