简体   繁体   English

图像未显示python tkinter

[英]Image not shown python tkinter

I want to input an image in my program, when I do this code 当我执行此代码时,我想在程序中输入图像

from tkinter import *

root = Tk()

image1 = PhotoImage(file='dog.gif')
label1 = Label(root, image=image1)
label1.pack()

root.mainloop()

The image will appear, but when I do this code 图像将出现,但是当我执行此代码时

from tkinter import *

class Image():
    def __init__(self, master):
        self.master = master

        self.display_image()

    def display_image(self):
        self.image = PhotoImage(file='dog.gif')
        self.label1 = Label(self.master, image=self.image)
        self.label1.pack()

if __name__ == '__main__':
    root = Tk()
    Image(root)
    root.mainloop()

The window will appear but the image was not shown 将出现窗口但未显示图像

If you create an image without keeping a strong reference somewhere, it will create a conflict between the garbage collector of Python and Tkinter : the reference stored in the Label prevents the complete destruction and the image will be blank. 如果创建图像时没有在某个地方保留强大的引用,则会在Python和Tkinter的垃圾回收器之间造成冲突:存储在Label的引用会阻止完全破坏,并且图像将为空白。

Also, be careful to not override base classes like Image , you'd better rename your own class My_Image 另外,请注意不要覆盖诸如Image类的基类,最好重命名自己的类My_Image

A simple workaround is to create a global variable containing the image: 一个简单的解决方法是创建一个包含图像的全局变量:

from tkinter import *

class My_Image():
    def __init__(self, master):
        self.master = master
        self.display_image()

    def display_image(self):

        self.label1 = Label(self.master, image=label1_img)
        self.label1.pack()


root = Tk()

label1_img = PhotoImage(file='dog.gif')
My_Image(root)

root.mainloop()

or you can even create a global variable to store the My_Image instance : 或者甚至可以创建一个全局变量来存储My_Image实例:

if __name__ == '__main__':
    root = Tk()
    img = My_Image(root)
    root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM