Tkinter隐藏主窗口后打开新窗口报错:pyimage10不存在
解决Tkinter中
tkinter.TclError: image "pyimage10" doesn't exist错误 问题根源
- 多Tk实例冲突:Tkinter要求整个应用只能存在一个主
Tk()实例,你的代码中Page1和Page2分别创建了独立的Tk(),导致Tcl上下文混乱,图片资源无法被正确识别。 - 图片引用被回收:PhotoImage对象如果没有持久化引用,会被Python垃圾回收机制销毁,导致Tkinter找不到对应图片。
- 路径变量未定义:Page2中未定义
OUTPUT_PATH和ASSETS_PATH,无法正确定位图片文件路径。
修正后的代码
Page1.py
from tkinter import Tk, Canvas, Button, PhotoImage from pathlib import Path OUTPUT_PATH = Path(__file__).parent ASSETS_PATH = OUTPUT_PATH / Path("./assets") def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path) window = Tk() window.geometry("703x981") window.configure(bg="#FFFFFF") button_image_6 = PhotoImage(file=relative_to_assets("button_6.png")) button_6 = Button( image=button_image_6, borderwidth=0, highlightthickness=0, command=lambda: nextPage(), relief="flat" ) button_6.place(x=415.0, y=793.0, width=86.0, height=78.0) def nextPage(): window.withdraw() from Page2 import create_page2 create_page2(window) if __name__ == "__main__": window.mainloop()
Page2.py
from tkinter import Toplevel, Canvas, PhotoImage from pathlib import Path OUTPUT_PATH = Path(__file__).parent ASSETS_PATH = OUTPUT_PATH / Path("./assets") def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path) def create_page2(parent): # 使用Toplevel创建子窗口,共享主窗口的Tcl上下文 window = Toplevel(parent) window.geometry("545x470") window.configure(bg="#FFFFFF") window.title('PythonGuides') canvas = Canvas( window, bg="#FFFFFF", height=470, width=545, bd=0, highlightthickness=0, relief="ridge" ) canvas.place(x=0, y=0) image_image_2 = PhotoImage(file=relative_to_assets("image_2.png")) canvas.create_image(272.0, 175.0, image=image_image_2) # 保存图片引用,防止被垃圾回收 canvas.image_ref = image_image_2 # 关闭子窗口时恢复主窗口 def on_close(): window.destroy() parent.deiconify() window.protocol("WM_DELETE_WINDOW", on_close)
关键修改说明
- 单一Tk实例:用
Toplevel替代Tk创建新窗口,复用主窗口的Tcl运行环境,解决资源冲突问题。 - 保留图片引用:将PhotoImage对象赋值给canvas的属性(如
canvas.image_ref),避免被Python垃圾回收销毁。 - 路径变量补全:在Page2中补充路径变量定义,确保图片文件能被正确找到。
- 函数化封装:将Page2的窗口创建逻辑封装为函数,通过参数传递主窗口,避免import时的执行顺序问题。
内容的提问来源于stack exchange,提问作者わんわんワコワコ
相关产品推荐
相关产品推荐

