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

情到浓时终转凉″ 提交于 2019-12-20 03:13:49

问题


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:

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?


回答1:


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.



来源:https://stackoverflow.com/questions/20938404/how-to-use-a-regular-expression-in-tkinter-text-search-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!