Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with tags in Tkinter text widget using python

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?

like image 711
Saul_Tigh Avatar asked Feb 25 '23 05:02

Saul_Tigh


2 Answers

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

like image 137
Thomas K Avatar answered Feb 26 '23 20:02

Thomas K


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

like image 20
Bryan Oakley Avatar answered Feb 26 '23 20:02

Bryan Oakley