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

父窗口图片在子窗口显示时报错pyimage9不存在的技术求助

解决Tkinter子窗口图片显示"pyimage不存在"问题

错误原因分析

你的代码存在两个核心问题:

  • 窗口对象被重复赋值:先创建了Tb.Window实例并完成一系列配置,随后又将create_account_window重新赋值为Toplevel(),导致之前的窗口配置全部失效,且新窗口未正确关联父窗口。
  • PhotoImage引用丢失:ImageTk.PhotoImage创建的对象如果没有被持久化引用,会被Python垃圾回收机制清理,导致图片无法显示,触发"pyimage不存在"错误。

修复方案及代码示例

方案1:基于ttkbootstrap窗口创建子界面

如果使用ttkbootstrap的Window作为子窗口,无需再创建Toplevel,直接复用已创建的窗口对象:

main_window.withdraw()

# 创建ttkbootstrap子窗口,关联父窗口main_window
create_account_window = Tb.Window(themename="darkly", title="TeXtCrYpTeR", master=main_window)
create_account_window.maxsize(width=550, height=335)
create_account_window.minsize(width=550, height=335)
create_account_window.resizable(False, False)

# 窗口居中
screen_width = create_account_window.winfo_screenwidth()
screen_height = create_account_window.winfo_screenheight()
app_width = 550
app_height = 335
x = (screen_width/2) - (app_width/2)
y = (screen_height/2) - (app_height/2)
create_account_window.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')

# 设置窗口图标
icon = r'padlock.ico'
create_account_window.iconbitmap(default=icon)

# 加载并显示图片,保留引用
img = Image.open("textcrypter.png")
frame = ImageTk.PhotoImage(img)
frame_place = tk.Label(create_account_window, image=frame)
# 将图片对象绑定到标签,防止被垃圾回收
frame_place.image = frame
frame_place.place(x=165, y=20)

# 启动子窗口主循环
create_account_window.mainloop()

方案2:使用Toplevel创建标准子窗口

如果需要用原生Toplevel,需确保关联父窗口,并保留图片引用:

main_window.withdraw()

# 创建Toplevel子窗口,指定父窗口为main_window
create_account_window = tk.Toplevel(main_window)
create_account_window.title("TeXtCrYpTeR")
create_account_window.maxsize(width=550, height=335)
create_account_window.minsize(width=550, height=335)
create_account_window.resizable(False, False)

# 窗口居中
screen_width = create_account_window.winfo_screenwidth()
screen_height = create_account_window.winfo_screenheight()
app_width = 550
app_height = 335
x = (screen_width/2) - (app_width/2)
y = (screen_height/2) - (app_height/2)
create_account_window.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')

# 设置窗口图标
icon = r'padlock.ico'
create_account_window.iconbitmap(default=icon)

# 加载并显示图片,保留引用
img = Image.open("textcrypter.png")
frame = ImageTk.PhotoImage(img)
frame_place = tk.Label(create_account_window, image=frame)
frame_place.image = frame
frame_place.place(x=165, y=20)

复用父窗口图片的优化

如果父窗口已加载过textcrypter.png,可以直接传递图片引用给子窗口,避免重复加载:

# 假设父窗口中已创建了photo对象:parent_photo = ImageTk.PhotoImage(Image.open("textcrypter.png"))
frame_place = tk.Label(create_account_window, image=parent_photo)
# 同样需要保留引用
frame_place.image = parent_photo

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:27:31