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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3781670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:42:36  来源:igfitidea点击:

How to highlight text in a tkinter Text widget

pythontexttkinter

提问by Lattice

I want to know how to change the style of certain words and expressions based on certain patterns.

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

I am using the Tkinter.Textwidget and I am not sure how to do such a thing (the same idea of syntax highlighting in text editors). I am not sure even if this is the right widget to use for this purpose.

我正在使用Tkinter.Text小部件,但我不确定如何做这样的事情(在文本编辑器中突出显示语法的想法相同)。即使这是用于此目的的正确小部件,我也不确定。

采纳答案by Bryan Oakley

It's the right widget to use for these purposes. The basic concept is, you assign properties to tags, and you apply tags to ranges of text in the widget. You can use the text widget's searchcommand to find strings that match your pattern, which will return you enough information apply a tag to the range that matched.

这是用于这些目的的正确小部件。基本概念是,您将属性分配给标签,并将标签应用于小部件中的文本范围。您可以使用文本小部件的search命令来查找与您的模式匹配的字符串,这将返回足够的信息,将标签应用于匹配的范围。

For an example of how to apply tags to text, see my answer to the question Advanced Tkinter text box?. It's not exactly what you want to do but it shows the basic concept.

有关如何将标签应用于文本的示例,请参阅我对Advanced Tkinter 文本框问题的回答. 这不完全是您想要做的,但它显示了基本概念。

Following is an example of how you can extend the Text class to include a method for highlighting text that matches a pattern.

下面是一个示例,说明如何扩展 Text 类以包含用于突出显示与模式匹配的文本的方法。

In this code the pattern must be a string, it cannot be a compiled regular expression. Also, the pattern must adhere to Tcl's syntax rules for regular expressions.

在这段代码中,模式必须是字符串,不能是编译后的正则表达式。此外,该模式必须遵守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")

回答by Amanuel Ephrem

Are you using tkinter.ttk? If so, import tkinter.ttk first then tkinter in your import statement list. That worked for me. Here's a picture

你在使用 tkinter.ttk 吗?如果是这样,请先导入 tkinter.ttk,然后在导入语句列表中导入 tkinter。那对我有用。这是一张图片