尝试将图像设置为第二个窗口时出现 pyimage4 错误 [英] pyimage4 error while trying to set image to 2nd window

查看:42
本文介绍了尝试将图像设置为第二个窗口时出现 pyimage4 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像设置为我单击按钮时打开的 tkinter 的第二个窗口
但它显示错误
_tkinter.TclError:图像pyimage4";不存在

im trying to set image to my 2nd window of tkinter which opens when i click on button
but it shows error
_tkinter.TclError: image "pyimage4" doesn't exist

def new_window():
    if(user.get()==username and passw.get()==password):
        window= Tk()
        window.geometry("%dx%d+0+0"%(w,h))
        image_new = Image.open("E:\\schoolmng\\try1.jpg")
        photo = ImageTk.PhotoImage(image_new)
        panel2 = Label(window, image=photo)
        panel2.pack()
    else:
        messagebox.showinfo("error","wrong password or username")

推荐答案

只需将 window = Tk() 更改为 window = Toplevel().之所以出现错误,是因为有两个Tk() 实例在运行,Tk() 实例不应超过1 个运行.因此,将其替换为 Toplevel() 将解决此问题.

Just change window = Tk() to window = Toplevel(). The reason why there is an error is because there is two instance of Tk() running, there should be not more than 1 instance of Tk() running. So replacing it with Toplevel() will fix this issue.

提示:

  • 你会得到一个额外的问题,这里没有显示图像,因为图像将被垃圾收集,要解决这个问题,你必须保持对图像的引用,或者说global photo在函数或 panel2.image = photo 之上.说其中任何一个都可以修复错误.

  • You will get an additional problem of no image displayed here, as the image will be garbage collected, to fix this you have to keep reference to the image, either by saying global photo on top of the function or panel2.image = photo. Saying either of this will fix the error.

解决方案 1:

def new_window():
    global photo
....

  • 解决方案 2:
  • ...
    photo = ImageTk.PhotoImage(image_new)
    panel2 = Label(window, image=photo)
    panel2.image = photo
    panel2.pack()
    ...
    

    希望您的问题得到解决,如果还有错误,请告诉我.

    Hope your issues are solved, if any more errors, do let me know.

    干杯

    这篇关于尝试将图像设置为第二个窗口时出现 pyimage4 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆