So, I've been learning how to use the tkinter package and I've come across a problem. After a researching a bit, I found out how to display jpeg images in my window, which I was successfully able to do. However, when I tried to do the exact same thing, but using a button to open a new window and displaying the same jpeg file, I'm getting a lot of errors.
I've also tried keeping reference of my image, as stated Here, but with no sucess.
Code that worked (displaying jpeg image in the main window):
import tkinter as tk
from PIL import ImageTk, Image
win = tk.Tk()
win.title("Test")
img = ImageTk.PhotoImage(Image.open("Photo.jpg"))
imglabel = tk.Label(win, image = img).grid(row=1, column=1)
win.mainloop()
Code that didn't work (opening the same jpeg file in a second window):
import tkinter as tk
from PIL import ImageTk, Image
win = tk.Tk()
win.title("Test")
def second_win():
win = tk.Tk()
win.title("Test2")
img = ImageTk.PhotoImage(Image.open("Photo.jpg"))
imglabel = tk.Label(win, image = img).grid(row=1, column=1)
button1 = tk.Button(win, text="Test2", command=second_win, height=5, width=20).pack()
win.mainloop()
The second code results in this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/User/PycharmProjects/Test/test", line 11, in second_win
imglabel = tk.Label(win, image = img).grid(row=1, column=1)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2766, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist