我想知道是否可以在Tkinter的Text小部件中为特定关键字着色。我基本上是在尝试编写一个编程文本编辑器,因此if
语句可能是一种颜色而else
语句可能是另一种颜色。谢谢阅读。
答案 0 :(得分:0)
执行此操作的一种方法是将函数绑定到Key事件,该事件搜索匹配的字符串并将标记应用于修改该字符串属性的任何匹配字符串。这是一个例子,有评论:
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()
改编自here
的示例有关Text
小部件here