求助:运行tkinter代码时canvas.create_text无法显示文本
Tkinter Canvas文本不显示的解决方案
你的代码里文本未显示的核心问题是文本位置重叠,以及字体名称拼写错误,调整后即可正常显示:
问题排查
- 第二个
create_text的坐标(200,150)与标题文本(400,150)处于同一水平线,导致文本重叠,视觉上无法区分; - 字体名称拼写错误:
"Ariel"应为"Arial",部分环境下可能导致字体加载异常; - 额外提醒:若
PhotoImage在函数内定义,需保留引用避免被垃圾回收(你的全局定义是正确的,无需修改)。
修正后的代码
from tkinter import * BACKGROUND_COLOR = "#B1DDC6" window = Tk() window.title("Flash Card") window.config(padx=50, pady=50, bg=BACKGROUND_COLOR) canvas = Canvas(width=800, height=526) front_image = PhotoImage(file="images/card_front.png") canvas.create_image(400, 263, image=front_image) # 标题文本:居中显示在卡片上方 canvas.create_text(400, 150, text="Title", font=("Arial", 40, "italic"), fill="black") # 内容文本:居中显示在卡片垂直中间位置 canvas.create_text(400, 263, text="word", font=("Arial", 40, "normal"), fill="black") canvas.config(bg=BACKGROUND_COLOR, highlightthickness=0) canvas.grid(column=0, row=0, columnspan=2) window.mainloop()
关键调整
- 调整内容文本的坐标为
(400,263),与标题上下分布,避免重叠; - 修正字体名称拼写为
"Arial"; - 显式指定
fill="black",确保文本与卡片背景形成清晰对比(若你的卡片背景为浅色)。
内容的提问来源于stack exchange,提问作者josephine omondi
相关产品推荐
相关产品推荐

