Python Tkinter 显示在列表框中访问的图像

Python Tkinter show image acessed on a listbox

我正在尝试制作一个 python 脚本来显示在列表框中访问的图像。我在互联网上获得的这段代码有效:

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()

但是当我尝试调整它时,列表框停止工作了。

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()

我错过了什么?

您必须使用标签的 configure 方法,并在某处存储对图像的引用。

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