2017-03-23 122 views
0

我有一个Text小部件是不可编辑的,其中可以使用Entry小部件添加文本。我想在Text小部件的某些文本比取决于在发送的文本类型的其余部分不同颜色的 例如根据类型的一个可能的输出可能是:Tkinter Text Widget颜色特定文本

*Line one text* (color: Black) 
*Line two text* (color: Blue) 
*Line three text* (color: Black) 

从我有发现似乎这是可以使用tag_addtag_configure方法的Text小工具有,但我不确定如何做到这一点。

我有以下的方法追加文本到Text小部件,改变文字的颜色的能力:

def append_to_display(self, text, color=standard): 
    self.display.configure(state=NORMAL) 
    self.display.tag_configure("color", foreground=color) 
    self.display.insert(END, text + "\n", "color") 
    self.display.configure(state=DISABLED) 

但是,如果我改变颜色为“绿色”它不会改变它仅用于发送文本,它会更改所有文本。

那么,如何让它只用于发送文本?

另外请注意,我正在运行的Python 3.6.1

+0

的可能的复制[如何改变在Tkinter的文本组件某些字的颜色?(http://stackoverflow.com/questions/14786507/how-to-change-the-color-of- tkinter-text-widget中的某些词) –

回答

2

你需要使用一个唯一的标签名称为每种颜色。

def append_to_display(self, text, color=standard): 
    tag_name = "color-" + color 
    self.display.tag_configure(tag_name, foreground=color) 
    ... 
    self.display.insert(END, text + "\n", tag_name) 
    ... 
+0

非常感谢你,这工作完美! – Ryan

相关问题