4

I'm trying color the text in the Tkinter text widget with help of tags in this way:

text = self.text_field.get(1.0, 'end') #text_field is a text widget
s = re.findall("\d+", text)
for i in s:
    self.text_field.tag_add(i, '1.0', 'end')
    self.text_field.tag_configure(i, background='yellow', 
                                  font='helvetica 14 bold', relief='raised')

The idea is that all tags are being dynamically created, because I get numbers from text widget and they can have any length. This code colors all text in the widget, but I need only numbers to be colored.

Any suggestions?

2 Answers 2

5

When you do

tag_add(i, '1.0', 'end')

You're making a tag that covers the whole text field. You need to just add the text on the numbers, using the .start() and .stop() methods of the regex match.

There's an example for doing syntax highlighting here:
http://forums.devshed.com/python-programming-11/syntax-highlighting-172406.html

Sign up to request clarification or add additional context in comments.

3 Comments

Could/would you update your link to point directly at the example being referred to?
@martineau: sorry, it looks like that site's URL structure has changed, and I don't know how to get back to that post.
I think I found it. Since the code is short (and open source), I suggest you add it to your answer as well as link to it.
4

There is an answer to a similar question that shows how to extend the text widget to have a method that highlights text based on a regular expression. For examples see How to highlight text in a tkinter Text widget

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.