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

如何在Tkinter的Canvas上隐藏文本并解决相关运行报错

问题根因
  • 你错误覆盖了subtext变量的值:canvas.create_text返回的是Canvas内文本元素的唯一ID,后续你写的subtext = Text直接把这个ID替换成了Tkinter的Text类本身,调用类的实例方法自然会抛出type object 'Text' has no attribute 'tk'的错误。
  • 你用错了控制显隐的方法:pack_forget是给通过pack布局的独立控件使用的,Canvas内部绘制的元素需要调用Canvas自带的方法操作。
解决方法

要隐藏Canvas上的文本元素,调用canvas.itemconfigure()方法,将对应元素的state属性设置为HIDDEN即可,需要重新显示时改回NORMAL即可。如果需要永久删除该元素,调用canvas.delete(subtext)即可。

如果你的需求是更新文本内容,不需要先删再建,直接修改text属性就行,示例:canvas.itemconfigure(subtext, text="新的文本内容")

修正后代码
canvas.place(x = 0, y = 0)

subtext = canvas.create_text(
    343.0,
    179.0,
    anchor="nw",
    text="What made you here?",
    fill="#000000",
    font=("Roboto Condensed", 89 * -1),
)

# 删掉原来的subtext = Text这行错误代码
def Jokes():
    joke = random.choice(jokes)
    print(joke)
    # 隐藏文本
    canvas.itemconfigure(subtext, state="hidden")
    # 如果要更新为笑话内容,用下面这行即可
    # canvas.itemconfigure(subtext, text=joke)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:45:02