Python Tkinter在列表框中显示图像

时间:2015-07-08 21:40:59

标签: python tkinter 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()

我错过了什么?

1 个答案:

答案 0 :(得分:2)

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

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