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

时间:2018-11-22 06:58:46

标签: python image tkinter

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

这是我的错误代码

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()

1 个答案:

答案 0 :(得分:1)

之所以会出现这样的区域,是因为在图像加载到窗口之前调用了root.destroy。此外,您不能使用两个TK实例,而必须使用Toplevel来检查链接了解得更好。

除了要在toplevel中显示图像,还需要为其创建引用,以便不会对其进行垃圾收集Display image in Toplevel window 我是这样label1.image = sub来做的。

我还使用image subsample来演示如何调整图像大小sub = photo2.subsample(5, 5)选中此link来阅读

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()