【问题标题】:Tkinter Text Widget Keyword ColouringTkinter 文本小部件关键字着色
【发布时间】:2014-04-16 21:29:28
【问题描述】:

我想知道是否可以在 Tkinter 的 Text 小部件中为特定关键字着色。我基本上是在尝试制作一个编程文本编辑器,所以if 语句可能是一种颜色,else 语句可能是另一种颜色。谢谢阅读。

【问题讨论】:

标签: python python-2.7 tkinter syntax-highlighting


【解决方案1】:

执行此操作的一种方法是将函数绑定到 Key 事件,该事件搜索匹配的字符串并将标记应用于修改该字符串属性的任何匹配字符串。这是一个带有 cmets 的示例:

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

【讨论】:

  • 谢谢,现在可以了
  • 是否有可能将所有整数添加到突出显示的单词中?还是所有带括号的单词?
  • 你的意思是把0-9加到字典里吗?如果是这样,是的,这是可能的。您可以添加任何您想要的键作为键,只要它的格式可以接受。
  • 我的意思是用户将输入“他们想要的任何东西”,只要它在“”中,它就会被着色。
猜你喜欢
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2019-06-14
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多