如何更改tkinter画布中文本对象中间单个单词的颜色



我在画布中有多行文本,我想更改单个单词的颜色,但我无法使用insert((进行更改,有办法吗?此外,如何在具有多行的create_text((对象上找到最后一个单词的位置?

from tkinter import font
import tkinter as tk
root = tk.Tk()
c = tk.Canvas(root)
c.pack(expand=1, fill=tk.BOTH)
fn = "Helvetica"
fs = 24
font = font.Font(family=fn, size=fs)

word1 = "I would like the last word of this phrase to be another color, maybe "
word2 = "red"
word3 = "... some other text that should be black again"
t1 = c.create_text(50,50,text=word1, anchor='nw', font=font, width=600)
#I would like this next word to be another color (red, green...)
c.insert(t1, "end", word2)
#then I would like it to be black again
c.insert(t1, "end", word3)
root.geometry('800x500+200+200')
root.mainloop()

测试此代码;

import tkinter as tk
from tkinter import font
root = tk.Tk()
c = tk.Canvas(root)
c.pack(expand=1, fill=tk.BOTH)
fn = "Helvetica"
fs = 24
font = font.Font(family=fn, size=fs)
sentence = '''
I would like the last word of this phrase to be another color, maybe red ... some other text that should be black again
'''
def change_color(sentence, color, start_p, end_p):
sentence = sentence.rstrip()
t1 = c.create_text(50, 50, text=sentence, anchor='nw', font=font, width=600)
t2 = c.create_text(50, 50, text=sentence[:end_p], anchor='nw', font=font, width=600, fill=color)
t3 = c.create_text(50, 50, text=sentence[:start_p], anchor='nw', font=font, width=600)

change_color(sentence=sentence, color="red", start_p=70, end_p=73)
root.geometry('800x500+200+200')
root.mainloop()

start_p是要改变颜色的子串的开始位置,end_p是结束位置。

MAYBE Using ANSI ESCAPE CODE
class ANSI():
def background(code):
return "33[{code}m".format(code=code)
def style_text(code):
return "33[{code}m".format(code=code)
def color_text(code):
return "33[{code}m".format(code=code)

def ANSISET(background,color,style,words) :
return ANSI.background(background) + ANSI.color_text(color) + ANSI.style_text(style) + " " + words
sentence ="I would like the last word of this phrase to be another 
color, maybe {} ... some other text that should be black again".format(ANSI(49,31,1,"red"))
#Default Foreground Color Code=39 AND Background Color Code=49 (RESET=0)
Note: the Reset color is the reset code that resets all colors and text effects, Use Default color to reset colors only
#background: allows background formatting. Accepts ANSI codes between 40 and 47, 100 and 107
#style_text: corresponds to formatting the style of the text. Accepts ANSI code between 0 and 8
#color_text:  Corresponds to the text of the color. Accepts ANSI code between 30 and 37, 90 and 97

最新更新