0

I want to look for a selected keyword and change its font color in a label text.

The code below that print in terminal.

import colorama as color
text = 'This is a long strings. How many strings are there'
x = 'strings'

if x in text:
    print(text.replace(x,"{}{}{}".format(color.Fore.RED, x, color.Fore.RESET)))
root.mainloop()

The code works great in terminal. After that, i try to apply the print code into label

from tkinter import *
root = Tk()
Label(root, text=text.replace(x,"{}{}{}".format(color.Fore.RED, x, color.Fore.RESET)))

The output after i applied become something like this in label:

This is a long 口[31mstrings. How many 口[31mstrings are there

I have look around the solutions, and found that colorama only works on terminal. Is there any better way to change the string's font-color in GUI? Thank you !

Bryan Oakley
  • 310,202
  • 36
  • 445
  • 584
Leow
  • 13
  • 3

1 Answers1

1

I have found solution from this Link here.

And i apply it into my code and it works like what it want.

import tkinter as tk
from tkinter import *

root = Tk()
texts = 'This is a long strings. How many strings are there'
x = 'strings'

if x in texts:
    text = CustomText(root)   #This is a class that i use to look to highlight x string in texts
    text.insert(END, texts)
    text.tag_configure("red", foreground="#ff0000")
    text.highlight_pattern(x, "red")
    

text.grid(row = 0 ,column = 1)
root.mainloop()

And Here is the image:

Output

Thank you for @j_4321 and @Bryan Oakley.

Leow
  • 13
  • 3