views:

36

answers:

2

Hello guys. I wanna know how to change the style of certain words, expressions .. etc based on certain pattens.
I am using the Tkinter.Text widget and I am not sure how can we do such thing (The same idea of syntax highlighting in text editors). I am not sure even if this is the right widget to use for that purpose.

A: 

Look at text widget tags.

Mark
+2  A: 

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 search command to find strings that match your pattern, which will return you enough information apply a tag to the range that matched.

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.

Here's an example of how you can extend the Text class to include a method for highlighting text that matches a pattern (barely tested, I just threw it together for this answer and haven't tested it much)

class CustomText(tk.Text):
    '''A text widget with a new method, HighlightPattern 

    example:

    text = CustomText()
    text.tag_configure("red",foreground="#ff0000")
    text.HighlightPattern("this should be red", "red")

    The HighlightPattern 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 HighlightPattern(self, pattern, tag, start="1.0", end="end"):
        '''Apply the given tag to all text that matches the given pattern'''

        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart",start)
        self.mark_set("matchEnd",end)
        self.mark_set("searchLimit", end)

        count = tk.IntVar()
        while True:
            index = self.search(pattern, "matchEnd","searchLimit",count=count)
            if index == "": break
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index,count.get()))
            self.tag_add(tag, "matchStart","matchEnd")
Bryan Oakley