You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何修改Tkinter Canvas组件内文本的颜色?

解决Tkinter Canvas文本颜色修改问题

你不需要替换成Text组件,直接在Canvas的文本创建逻辑里就能修改颜色,两种简单方法如下:

方法一:创建文本时直接指定颜色

在create_text方法里添加fill参数,直接设置文本颜色:

from tkinter import *
import random

root = Tk()

background = PhotoImage(file = 'background.png')
win_screen_image = PhotoImage(file = 'win_screen.png')
lose_screen_image = PhotoImage(file = 'lose_screen.png')


def introductionCanvas():
    intro_screen = Canvas(root, height = 720, width = 1280)
    intro_screen.create_image(0, 0, image = background, anchor = 'nw')
    intro_screen.pack()
    # 通过fill参数设置文本颜色,示例为白色
    intro_text = intro_screen.create_text(240, 80, font = 'Calibri 18', 
                                         text = '     Welcome, Witcher\nPlease Enter Your Name:',
                                         fill='white')

introductionCanvas()
root.mainloop()

方法二:用标签配置动态修改颜色

如果需要后续动态调整颜色,可以给文本添加标签,再通过tag_configure修改:

from tkinter import *
import random

root = Tk()

background = PhotoImage(file = 'background.png')
win_screen_image = PhotoImage(file = 'win_screen.png')
lose_screen_image = PhotoImage(file = 'lose_screen.png')


def introductionCanvas():
    intro_screen = Canvas(root, height = 720, width = 1280)
    intro_screen.create_image(0, 0, image = background, anchor = 'nw')
    intro_screen.pack()
    # 创建文本时绑定自定义标签
    intro_text = intro_screen.create_text(240, 80, font = 'Calibri 18', 
                                         text = '     Welcome, Witcher\nPlease Enter Your Name:',
                                         tags=('intro_text_tag',))
    # 通过标签配置颜色,示例为黄色
    intro_screen.tag_configure('intro_text_tag', fill='yellow')

introductionCanvas()
root.mainloop()

关于替换Text组件报错的说明

Text是Tkinder的独立组件,不能直接用Canvas的方法添加。如果非要在Canvas里嵌入Text,需要用create_window方法,但完全没必要——Canvas自带的文本功能已经能满足需求,额外引入Text只会增加复杂度。

内容的提问来源于stack exchange,提问作者soggothememe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:55:26