Question

I was wondering if it was possible to color specific keywords within a Text widget in Tkinter. I am basically trying to make a programming text editor, so maybe the if statement would be one color and the else statement would be another. Thanks for reading.

Was it helpful?

Solution

One way to do this is to bind a function to a Key event that searches for matching strings and applies a tag to any matching strings that modifies that string's attributes. Here's an example, with comments:

from Tkinter import *

# dictionary to hold words and colors
highlightWords = {'if': 'green',
                  'else': 'red'
                  }

def highlighter(event):
    '''the highlight function, called when a Key-press event occurs'''
    for k,v in highlightWords.iteritems(): # iterate over dict
        startIndex = '1.0'
        while True:
            startIndex = text.search(k, startIndex, END) # search for occurence of k
            if startIndex:
                endIndex = text.index('%s+%dc' % (startIndex, (len(k)))) # find end of k
                text.tag_add(k, startIndex, endIndex) # add tag to k
                text.tag_config(k, foreground=v)      # and color it with v
                startIndex = endIndex # reset startIndex to continue searching
            else:
                break

root = Tk()
text = Text(root)
text.pack()

text.bind('<Key>', highlighter) # bind key event to highlighter()

root.mainloop()

Example adapted from here

More on Text widget here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top