在 NewWindow 上创建图像还为时过早

我想在新窗口中显示图像,但出现错误。


这是我的错误代码


photo = PhotoImage(file='img/dog')

File "C:\Users\Hyojae\Anaconda3\lib\tkinter\__init__.py", line 3542, in __init__

Image.__init__(self, 'photo', name, cnf, master, **kw)

File "C:\Users\Hyojae\Anaconda3\lib\tkinter\__init__.py", line 3486, in __init__

raise RuntimeError('Too early to create image')

RuntimeError: Too early to create image

这是我的代码示例。


我会很感激你的帮助。


from tkinter import *


def messageWindow():

    win = Tk()

    win.geometry('300x200')


    root.destroy()



    photo2 = PhotoImage(file="img/dog1.gif")

    label1 = Label(win, image=photo2)

    label1.grid(row=6)


    Button(win, text='OK', command=win.destroy).grid(row = 5, columnspan = 2)


    win.mainloop()


root = Tk()

photo = PhotoImage(file="img/dog2.gif")

label1 = Label(root, image=photo)

label1.pack()



Button(root, text='Bring up Message', command=messageWindow).pack()



root.mainloop()


HUX布斯
浏览 230回答 1
1回答

30秒到达战场

你得到这样的区域是因为你root.destroy在图像加载到窗口之前调用。此外,你不能使用两个TK实例,你必须使用Toplevel检查链接以更好地理解。除此之外,要在其中显示图像,toplevel您需要为它创建引用,这样它就不会被垃圾收集在 我这样做的Toplevel 窗口中显示图像label1.image = sub。我还image subsample用来演示如何调整图像大小sub = photo2.subsample(5, 5)检查此链接以了解它from tkinter import *def messageWindow():    win = Toplevel()    win.geometry('300x200')    root.withdraw() # THIS HIDE THE WINDOW    photo2 = PhotoImage(file="img/dog1.gif")    sub = photo2.subsample(5, 5)    label1 = Label(win, image=sub)    label1.image = sub    label1.grid(row=6)    Button(win, text='OK', command=win.destroy).grid(row = 5, columnspan = 2)root = Tk()photo = PhotoImage(file="img/dog1.gif")sub1 = photo.subsample(3,3)label1 = Label(root, image=sub1)label1.pack()B = Button(root, text='Bring up Message', command=messageWindow)B.place(x=200, y=300)root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python