在句子中查找字符串并更改字符串的颜色并在 tkinter 标签中显示 python

Find a string in sentence and change the string's color and display in tkinter label python

我想查找选定的关键字并更改其在标签文本中的字体颜色。

下面的代码在终端打印。

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

该代码在终端中运行良好。之后,我尝试将打印代码应用到标签

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

我应用后的输出在标签中变成这样:

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

我查看了解决方案,发现 colorama 仅适用于终端。有没有更好的方法在 GUI 中更改字符串的字体颜色?谢谢!

我从这个 Link here.

中找到了解决方案

我将它应用到我的代码中,它按预期工作。

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

图片如下:

Output

感谢@j_4321 和@Bryan Oakley。