简体   繁体   中英

How to show image in tkinter using pillow with OOP

I am making a program where I need to at some point display an image onto a frame at the press of a button. I am using an object oriented approach but it won't display the image. If I do something like:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
pic = Image.open("image.jpg")
tkpic = ImageTk.PhotoImage(pic)
label = Label(root, image=tkpic)
label.pack()
root.mainloop()

that works fine. But if I create a frame and try to display the picture like this:

from tkinter import *
from PIL import Image, ImageTk

class picframe(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        button = Button(self, text="show", command=self.showpic)
        button.pack()
    def showpic(self):
        pic = Image.open("image.jpg")
        tkpic = ImageTk.PhotoImage(pic)
        label = Label(self, image=tkpic)
        label.pack()

root = Tk()

frame = picframe(root)
frame.pack()

root.mainloop()

When I press the button it expands the window as if it was trying to display the image but nothing shows up it just becomes a wider window. So what am I doing wrong?

Thank you in advance!

As the picture is created in a function the reference tkpic will be garbage collected when the function exits. You need to save a reference to the image:

def showpic(self):
    pic = Image.open("image.jpg")
    tkpic = ImageTk.PhotoImage(pic)
    label = Label(self, image=tkpic)
    label.image = tkpic  # Save reference to image
    label.pack()

Alternatively you can ensure the persistance of the image reference by making it an instance variable:

def showpic(self):
    pic = Image.open("images/beer.png")
    self.tkpic = ImageTk.PhotoImage(pic)
    label = Label(self, image=self.tkpic)
    label.pack()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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