为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUX布斯 2021-08-24 19:20:50
我想在新窗口中显示图像,但出现错误。这是我的错误代码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 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

你得到这样的区域是因为你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()


查看完整回答
反对 回复 2021-08-24
  • 1 回答
  • 0 关注
  • 229 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信