可以在主窗口中打开jpeg文件,但不能在第二个窗口中打开它

时间:2019-08-28 14:09:49

标签: python tkinter

因此,我一直在学习如何使用tkinter软件包,但遇到了一个问题。经过一番研究,我发现了如何在窗口中显示jpeg图像,这是我能够成功完成的。但是,当我尝试做完全相同的事情,但是使用按钮打开一个新窗口并显示相同的jpeg文件时,我遇到了很多错误。

我也尝试过参考Here,但没有成功。

有效的代码(在主窗口中显示jpeg图像):

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

无效的代码(在第二个窗口中打开相同的jpeg文件):

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

第二个代码导致此错误:

Tkinter回调中的异常

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

0 个答案:

没有答案