尝试将图像设置为第二个窗口时出现 pyimage4 错误

编程入门 行业动态 更新时间:2024-10-27 07:17:57
本文介绍了尝试将图像设置为第二个窗口时出现 pyimage4 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试将图像设置为我单击按钮时打开的 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 06:16:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第二个   设置为   图像   窗口   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!