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.
Asked
Active
Viewed 1,620 times
2

user3286192
- 95
- 1
- 7
-
possible duplicate of [How to change the color of certain words in the tinter text widget?](http://stackoverflow.com/questions/14786507/how-to-change-the-color-of-certain-words-in-the-tkinter-text-widget) – Quintec Apr 16 '14 at 23:17
-
click the link to get the answer – Quintec Apr 16 '14 at 23:17
-
I tried this but unfortunately I think that this tutorial shows how to color pre-inserted words, not words that the user types in. – user3286192 Apr 17 '14 at 01:15
-
I also get the error 'highlight_pattern' does not exist. – user3286192 Apr 17 '14 at 01:18
1 Answers
2
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

atlasologist
- 3,824
- 1
- 21
- 35
-
-
By any chance is it possible to add all integers to the highlight words? Or all words with parenthesis? – user3286192 Apr 17 '14 at 16:52
-
Do you mean adding 0-9 to the dictionary? If so, yes, that is possible. You can add whatever you want as a key, as long as it's in an acceptable format. – atlasologist Apr 17 '14 at 17:22
-
I mean the user will enter "what ever they want" and as long as it is in "", it will be colored. – user3286192 Apr 17 '14 at 17:33