微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在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,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是要更改颜色的子字符串的结束位置。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。