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

Tkinter报错Too early to create image: no default root window

问题原因

Tkinter 所有可视化资源(包括PhotoImage图片、各类控件)都必须依附于已完成初始化的根窗口(Tk实例)才能创建。
你的代码将PhotoImage初始化逻辑写在了全局作用域,代码运行到图片加载行时,Application根窗口实例还未创建,Tkinter 找不到可挂载资源的默认根窗口,就会抛出Too early to create image: no default root window的错误,该问题和是否调用.destroy()方法无关。

修复步骤
  • 删除全局作用域下所有PhotoImage初始化的代码,禁止在根窗口实例化前创建任何Tkinter相关的资源对象
  • 在Application类的__init__方法中,完成根窗口初始化(执行完tk.Tk.__init__())之后,再加载所有图标资源,并且将图片存为实例属性——这一步同时可以避免Python垃圾回收机制回收图片资源导致的界面图片不显示问题
  • 各个页面类如果需要使用图标,通过传入的controller参数(即Application实例)访问对应的图片属性即可
修复后核心代码参考
class Application(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # 根窗口初始化完成后再加载所有图片,存为实例属性
        icon_path = r"C:\Users\vince\OneDrive\Desktop\ICONS"
        self.photo1 = PhotoImage(file=fr"{icon_path}\thumbs up.png")
        self.photo2 = PhotoImage(file=fr"{icon_path}\thumbs down.png")
        self.photo3 = PhotoImage(file=fr"{icon_path}\flower.png")
        self.photo4 = PhotoImage(file=fr"{icon_path}\poop.png")
        self.photo5 = PhotoImage(file=fr"{icon_path}\dry floor.png")
        self.photo6 = PhotoImage(file=fr"{icon_path}\wet floor.png")
        self.photo7 = PhotoImage(file=fr"{icon_path}\no toilet paper.png")
        self.photo8 = PhotoImage(file=fr"{icon_path}\toilet paper.png")
        self.photo9 = PhotoImage(file=fr"{icon_path}\no toilet.png")
        self.photo10 = PhotoImage(file=fr"{icon_path}\toilet.png")
        self.photo11 = PhotoImage(file=fr"{icon_path}\QR CODE.png")

        # creating a window
        window = tk.Frame(self)
        window.pack()
        window.grid_rowconfigure(0, minsize=500)
        window.grid_columnconfigure(0, minsize=800)
        self.frames = {}
        for F in (Page1, Page2, Page3, Page4, Page5, Confirmation1, Confirmation2, Confirmation3, Confirmation4):
            frame = F(window, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(Page1)
    def show_frame(self, page):
        frame = self.frames[page]
        frame.tkraise()
        self.title("Application")

额外注意:你的代码同时使用from tkinter import *和from tkinter.ttk import *,后导入的ttk模块下的Label、Button组件会覆盖tk模块下的同名组件,容易出现控件样式、参数不符合预期的问题,建议后续统一使用tk.前缀调用tk原生组件,ttk.前缀调用ttk组件,避免命名冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 06:48:30