[英]Find a string in sentence and change the string's color and display in tkinter label python
I want to look for a selected keyword and change its font color in a label text.我想在 label 文本中查找选定的关键字并更改其字体颜色。
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之后,我尝试将打印代码应用到 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:我申请后的 output 在 label 中变成了这样:
This is a long 口[31mstrings.这是一个长口[31mstrings。 How many 口[31mstrings are there有多少口[31mstrings
I have look around the solutions, and found that colorama only works on terminal.我查看了解决方案,发现 colorama 仅适用于终端。 Is there any better way to change the string's font-color in GUI?有没有更好的方法来更改 GUI 中字符串的字体颜色? Thank you !谢谢 !
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:这是图像:
Thank you for @j_4321 and @Bryan Oakley.感谢@j_4321 和@Bryan Oakley。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.