2017-03-23 157 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

相關問題