Python Tkinter文本小部件关键字着色
我想知道是否有可能在Tkinter的文本小部件中为特定的关键字着色。我基本上是在尝试制作一个编程文本编辑器,因此,Python Tkinter文本小部件关键字着色,python,python-2.7,tkinter,syntax-highlighting,Python,Python 2.7,Tkinter,Syntax Highlighting,我想知道是否有可能在Tkinter的文本小部件中为特定的关键字着色。我基本上是在尝试制作一个编程文本编辑器,因此,if语句可能是一种颜色,else语句可能是另一种颜色。谢谢你的阅读 一种方法是将函数绑定到一个键事件,该事件搜索匹配字符串,并将标记应用于修改该字符串属性的任何匹配字符串。下面是一个示例,并附有注释: from Tkinter import * # dictionary to hold words and colors highlightWords = {'if': 'green'
if
语句可能是一种颜色,else
语句可能是另一种颜色。谢谢你的阅读 一种方法是将函数绑定到一个键事件,该事件搜索匹配字符串,并将标记应用于修改该字符串属性的任何匹配字符串。下面是一个示例,并附有注释:
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()
从Tkinter导入*
#保存单词和颜色的字典
highlightWords={'if':'green',
“其他”:“红色”
}
def荧光灯(事件):
''当按键事件发生时调用的突出显示函数''
对于highlightWords.iteritems()中的k,v:#迭代dict
startIndex='1.0'
尽管如此:
startIndex=text.search(k,startIndex,END)#搜索k的出现
如果开始索引:
endIndex=text.index(“%s+%dc%”(startIndex,(len(k)))#查找k的结尾
text.tag_添加(k,startIndex,endIndex)#将标记添加到k
text.tag_config(k,foreground=v)#并用v将其着色
startIndex=endIndex#重置startIndex以继续搜索
其他:
打破
root=Tk()
text=文本(根)
text.pack()
text.bind(“”,highlighter)#将键事件绑定到highlighter()
root.mainloop()
改编自
更多关于
Text
widget可能重复的点击链接获取答案我尝试了这个方法,但不幸的是,我认为本教程展示了如何为预插入的单词着色,而不是用户键入的单词。我还发现错误“突出显示模式”不存在。谢谢,现在它使since有可能将所有整数添加到突出显示的单词中吗?还是所有带括号的单词?你的意思是在字典中添加0-9?如果是的话,是的,这是可能的。你可以添加你想要的任何东西作为密钥,只要它的格式可以接受。我的意思是用户将输入“他们想要什么”,并且只要它在“”中,它将被着色。