问题描述
我在画布中有多行文本,我想更改单个单词的颜色,但是我无法使用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,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,text=sentence[:end_p],width=600,fill=color)
t3 = c.create_text(50,text=sentence[:start_p],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是要更改颜色的子字符串的结束位置。