Search code examples
pythonregextkinterhighlight

How to use a regular expression in Tkinter text search method?


I want to find an area for highlighting within square brackets. These square brackets may contain any text: [A hello world] [B this is a tree] [A tkinter documentation is bad]

I want to highlight the words in the brackets that have "A" character with them, like this: enter image description here

To get the starting index and the number of the matched characters I tried this:

countVar = StringVar()
reg_area = re.compile(r'\[A.*\]')
index = text.search('1.0', reg_area, stopindex=END, count=countVar, regexp = True)

This does not work and I receive.

TclError: bad text index "<_sre.SRE_Pattern object at 0x3856d78>"

How do I find all occurences and correctly highlight them?


Solution

  • You have two problems. First, you are putting positional arguments in the wrong order. The first positional argument is expected to be the pattern, and the second positional argument is treated as the start index. Since your second argument is an instance of SRE_Pattern, you get the bad text index error.

    You need to change the order of your arguments so that your first argument is the pattern. The next two arguments should be the start and end indexes.

    Second, when you set regexp to True, you must still pass the pattern in as a string. The text widget will interpret that string as a regular expression. You cannot pass in a compiled regular expression.

    Here's an example that should work:

    index = text.search(r'\[A.*\]', "1.0", END, count=countVar, regexp=True)
    

    FWIW, this answer to the question Tkinter text highlighting in python gives an example of subclassing the Text class to add a method named highlight_pattern.