문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top