在句子中找到一个字符串,并在tkinter标签python中更改该字符串的颜色和显示

2024-03-28 11:08:09 发布

您现在位置: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中更改字符串的字体颜色?谢谢大家!


Tags: 代码textimport终端is颜色字体root
1条回答
网友
1楼 · 发布于 2024-03-28 11:08:09

我从这个链接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

相关问题 更多 >