Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the colour of text automatically inserted into tkinter widget

I have a text box widget that has three messages inserted into it. One is a start message, one an ending message, and one a message to alert when a 'unit' has been destroyed. I want the starting and ending messages to be black, but the destoyed messages (see where I have commented in the code) to be coloured red when inserted into the widget.

I'm not exactly sure how to go about doing this. I took a look at How to change the color of certain words in the tkinter text widget? and this would work, however it only changes the text properties if the text is selected using the mouse, whereas I want my text to be inserted in that colour automatically.

Any suggestions to point me in the right direction? I relatively new to Tkinter. I'm using 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()
like image 461
Alice Avatar asked Dec 01 '17 11:12

Alice


People also ask

How do you change the font color in TK?

You can use bg='#fff' or fg='f00' in tk.

What does text variable do in Tkinter?

In the case of textvariable , which is mostly used with Entry and Label widgets, it is a variable that will be displayed as text. When the variable changes, the text of the widget changes as well.


1 Answers

insert() has option tags so you can assign tag (or many tags) when you insert text.

And then you have to only assign color to this tag.

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()

enter image description here

like image 172
furas Avatar answered Oct 13 '22 04:10

furas