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

CustomTkinter多应用窗口背景图片加载失败问题求助

解决CustomTkinter跨窗口图片加载失败问题

错误原因

_tkinter.TclError: image "pyimage2" doesn't exist 错误源于两个核心问题:

  • Tkinter(CustomTkinter基于它)默认仅支持一个Tcl解释器,在同一个进程中创建多个CTk()主窗口会导致资源上下文冲突。
  • 你将图片作为类属性提前加载,这些资源会绑定到第一个窗口的Tcl实例,第二个窗口无法访问该上下文的资源。

解决方案

方案1:拆分为两个独立程序(符合你“两个文件两个应用”的需求)

将代码拆分为两个独立文件,通过subprocess启动第二个程序,确保两个进程完全隔离,避免Tcl上下文冲突。

文件1:app1.py

import customtkinter as ctk
from PIL import Image
import subprocess

def start_app2():
    # 根据实际路径调整启动命令
    subprocess.Popen(["python", "app2.py"])

class App1:
    def __init__(self):
        self.window1 = ctk.CTk()
        # 在实例方法内加载图片,绑定当前窗口上下文
        icon1 = Image.open('res\\font33543543.jpg')
        self.font1 = ctk.CTkImage(icon1, size=(600, 400))
        ctk.CTkLabel(self.window1, text='', image=self.font1).place(x=0, y=0)
        ctk.CTkButton(self.window1, text="启动App2", command=start_app2).place(x=10, y=10)
        self.window1.mainloop()

if __name__ == "__main__":
    App1()

文件2:app2.py

import customtkinter as ctk
from PIL import Image

class App2:
    def __init__(self):
        self.window = ctk.CTk()
        icon2 = Image.open('res\\font33543543.jpg')
        self.font2 = ctk.CTkImage(icon2, size=(600, 400))
        ctk.CTkLabel(self.window, text='', image=self.font2).place(x=0, y=0)
        self.window.mainloop()

if __name__ == "__main__":
    App2()

方案2:同一程序内使用子窗口

如果不需要独立进程,仅需同一程序内的两个窗口,改用CTkToplevel创建子窗口,共享主窗口的事件循环,避免多主窗口冲突。

import customtkinter as ctk
from PIL import Image

def start_app2(parent):
    App2(parent)

class App1:
    def __init__(self):
        self.window1 = ctk.CTk()
        icon1 = Image.open('res\\font33543543.jpg')
        self.font1 = ctk.CTkImage(icon1, size=(600, 400))
        ctk.CTkLabel(self.window1, text='', image=self.font1).place(x=0, y=0)
        ctk.CTkButton(self.window1, text="启动子窗口", command=lambda: start_app2(self.window1)).place(x=10, y=10)
        self.window1.mainloop()

class App2:
    def __init__(self, parent):
        # 创建子窗口而非新主窗口
        self.window = ctk.CTkToplevel(parent)
        icon2 = Image.open('res\\font33543543.jpg')
        self.font2 = ctk.CTkImage(icon2, size=(600, 400))
        ctk.CTkLabel(self.window, text='', image=self.font2).place(x=0, y=0)
        # 无需单独调用mainloop,主窗口事件循环已处理所有事件

if __name__ == "__main__":
    App1()

关键注意事项

  • 不要将图片作为类属性提前加载,应在实例的__init__方法内加载,确保资源绑定到当前窗口的Tcl上下文。
  • 避免嵌套调用mainloop(),Tkinter仅需一个主事件循环即可处理所有窗口事件。

内容的提问来源于stack exchange,提问作者Пётр Иванович

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:51:05