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

使用customtkinter显示图片时出现pyimage26不存在错误

解决Tkinter "pyimageXX doesn't exist" 错误

问题原因

你在代码中创建了第二个customtkinter.CTk()实例(info_window),而creeper_bg这类图片对象是和第一个主窗口绑定的。Tkinter的图片资源会关联到创建它的根窗口,跨根窗口引用就会触发"pyimageXX doesn't exist"错误。

解决方案

有两种可靠的修复方式:

方式1:使用CTkToplevel创建子窗口(推荐)

Tkinter程序应仅保留一个主根窗口,其他弹窗用CTkToplevel创建(基于主窗口的子窗口),这样可以共享主窗口的资源:

def info_button_callback():
    # 替换CTk()为CTkToplevel,传入主窗口对象main作为父窗口
    info_window = customtkinter.CTkToplevel(main)
    
    w = 300
    h = 200
    ws = info_window.winfo_screenwidth()
    hs = info_window.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    info_window.geometry('%dx%d+%d+%d' % (w, h, x, y))
    info_window.resizable(False, False)

    creeper_label = customtkinter.CTkLabel(
        info_window, width=70, height=70, image=creeper_bg, text="", corner_radius=0, fg_color="transparent", bg_color="transparent")
    creeper_label.place(x=10, y=100, anchor="w")

    # 移除info_window.mainloop(),主窗口的mainloop已在运行

方式2:在弹窗内部创建图片对象

将creeper_bg的定义移到info_button_callback内部,让图片和当前弹窗窗口绑定:

def info_button_callback():
    info_window = customtkinter.CTk()
    
    # 在弹窗内部创建关联当前窗口的图片
    creeper_bg = customtkinter.CTkImage(
        dark_image=Image.open("creeper_bg.png"), size=(70, 70))
    
    w = 300
    h = 200
    ws = info_window.winfo_screenwidth()
    hs = info_window.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    info_window.geometry('%dx%d+%d+%d' % (w, h, x, y))
    info_window.resizable(False, False)

    creeper_label = customtkinter.CTkLabel(
        info_window, width=70, height=70, image=creeper_bg, text="", corner_radius=0, fg_color="transparent", bg_color="transparent")
    creeper_label.place(x=10, y=100, anchor="w")

    info_window.mainloop()

注意事项

  • 优先选择方式1,符合Tkinter的设计规范,避免多根窗口带来的资源冲突问题
  • 确保图片路径正确,你已经验证过路径和格式,这部分无需再调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:30:17