Dynamically display jpg image in python Tkinter label

Asked

Viewed 3,054 times

3

I am trying to display a chosen image of a Listbox on a Label. The following code works:

import Tkinter as tk
from PIL import ImageTk, Image

window = tk.Tk()

path = 'img\\2015722_univ_sqs_sm.jpg'
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")

window.mainloop()

But when I try to load a listbox image it doesn’t work.

from Tkinter import *
from PIL import ImageTk, Image
import glob

files = glob.glob('img\\*.jpg')

class App:

    def __init__(self, root):

        self.l = Listbox(root, width = 50, height = 15)
        self.l.pack()
        self.l.bind('<<ListboxSelect>>', self.lol)

        self.c = Label(root)
        self.c.pack()

        for f in files:
            self.l.insert(END, f)

    def lol(self, evt):

        path = files[self.l.curselection()[0]]
        img = ImageTk.PhotoImage(Image.open(path))
        self.c.image = img
        self.c.pack()

root = Tk()
App(root)
root.mainloop()

Where am I going wrong?

1 answer

0


This snippet has solved:

self.c.image = img           # save reference
self.c.configure(image=img)  # configure the label

Browser other questions tagged

You are not signed in. Login or sign up in order to post.