更改自动插入到tkinter小部件中的文本颜色

Zac*_*Zac 4 python tkinter colors widget python-3.x

我有一个文本框小部件,其中插入了三个消息.一个是开始消息,一个是结束消息,另一个是在"单位"被销毁时发出警报的消息.我希望开始和结束消息是黑色的,但是当插入到小部件中时,破坏的消息(请参阅我在代码中评论的位置)将显示为红色.

我不确定如何去做这件事.我看了一下如何更改tkinter文本小部件中某些单词的颜色?如果使用鼠标选择文本,它只会更改文本属性,而我希望我的文本自动插入该颜色.

有什么建议指引我正确的方向?我比较新Tkinter.我正在使用Python 3.6.

import tkinter as tk
import random

class SimulationWindow():

    def __init__(self, master):

        #Initialise Simulation Window
        self.master = master
        self.master.geometry('1024x768') #w,h

        #Initialise Mainframe
        self.mainframe()

    def mainframe(self):

        #Initialise Frame
        self.frame = tk.Frame(self.master)
        self.frame.grid_columnconfigure(0, minsize = 100)
        self.frame.grid(row = 1, sticky = 'w')

        self.txtb_output = tk.Text(self.frame)
        self.txtb_output.config(width = 115, height = 30, wrap = tk.WORD)
        self.txtb_output.grid(row = 1, column = 0, columnspan = 3, padx = 50)

        btn_start = tk.Button(self.frame)
        btn_start.config(text = 'Start', borderwidth = 2, padx = 2, height = 2, width = 20)
        btn_start.bind('<Button-1>', self.start)
        btn_start.grid(row = 2, column = 1, padx = (0,65), pady = 20)


    def battle(self):
        if len(self.units) == 0:
            self.txtb_output.insert(tk.END, 'The battle has ended.\n')
        else:
            try:
                destroyed = random.randint(0,4)
                #I want the text here to be red
                self.txtb_output.insert(tk.END, 'The unit ' + self.units[destroyed] + ' has been destroyed.\n')
                self.units.remove(self.units[destroyed])
                self.frame.after(5000, self.battle)
            except:
                self.battle()

    def start(self, event):
        self.units = ['battle droid', 'battle droid', 'droid tank', 'super battle droid', 'battle droid']
        self.txtb_output.insert(0.0, 'The battle has begun.\n')
        self.battle()

def main():
    root = tk.Tk()
    main_window = SimulationWindow(root)
    root.mainloop()

main()
Run Code Online (Sandbox Code Playgroud)

fur*_*ras 9

insert()有选项,tags所以你可以在插入文本时帮助标记(或许多标记).

然后你必须只为这个标签指定颜色.

import tkinter as tk

root = tk.Tk()

txt = tk.Text(root)
txt.pack()

txt.tag_config('warning', background="yellow", foreground="red")

txt.insert('end', "Hello\n")
txt.insert('end', "Alert #1\n", 'warning')
txt.insert('end', "World\n")
txt.insert('end', "Alert #2\n", 'warning')

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述