在NewWind创造形象还为时过早

2024-03-29 15:53:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是我的错误代码

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

这是我的代码示例。在

谢谢你的帮助。在

^{pr2}$

Tags: toinpyinittkinterliblineusers
1条回答
网友
1楼 · 发布于 2024-03-29 15:53:27

您得到这样的区域是因为在图像加载到之前调用了root.destroy窗户。还有不能使用两个TK实例,必须使用Toplevel检查链接以更好地理解。在

除此之外,要在toplevel中显示图像,您需要为它创建引用,这样它就不会被垃圾回收Display image in Toplevel window 我就是这样做的。在

我还使用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()

相关问题 更多 >