Working with tags in Tkinter text widget using python

13,030

Solution 1

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

Solution 2

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

Share:
13,030
Saul_Tigh
Author by

Saul_Tigh

Updated on June 04, 2022

Comments

  • Saul_Tigh
    Saul_Tigh almost 2 years

    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?

  • martineau
    martineau over 9 years
    Could/would you update your link to point directly at the example being referred to?
  • Thomas K
    Thomas K over 9 years
    @martineau: sorry, it looks like that site's URL structure has changed, and I don't know how to get back to that post.
  • martineau
    martineau about 9 years
    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.