I want to display the image in a new window, but I get an error.
This is my error code
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
And this is my code sample.
I would appreciate your help.
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()
You are getting such area because you call root.destroy
before the image is loaded to the window.Also you can not use two TK
instance you have to use Toplevel check the link to understand better.
Aside that to display image in toplevel
you need to create reference for it so it will not be garbage collectedDisplay image in Toplevel window which i did this way label1.image = sub
.
I also use image subsample
to demonstrate how to resize image sub = photo2.subsample(5, 5)
check this link to read about it
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.