一旦你点击一个缩略图来显示图像?

时间:2014-02-11 13:12:04

标签: python python-3.x tkinter python-imaging-library

请帮助修复脚本。

import os, sys
import tkinter
from PIL import ImageTk, Image

DIR_IMGS = 'imgs'
DIR_THUMBS = 'thumbs'
imgfiles = os.listdir(DIR_IMGS)
thumbfiles = os.listdir(DIR_THUMBS)

root = tkinter.Tk()
root.geometry('900x700')
links = []


def showItem(imgfile):
    print(imgfile)
    pathImg = os.path.join(DIR_IMGS, imgfile)
    print(pathImg)
    renderImg = ImageTk.PhotoImage(file=pathImg)
    popup = tkinter.Toplevel()
    tkinter.Button(popup, image=renderImg).pack()   


def createThumbs():
    for imgfile in imgfiles:
        pathImg1 = os.path.join(DIR_IMGS, imgfile)
        pathImg2 = os.path.join(DIR_THUMBS, imgfile)

        openImg = Image.open(pathImg1)
        openImg.thumbnail((100, 100))
        openImg.save('thumbs/' + imgfile)


def outputButtons():
    for thumbfile in thumbfiles:
        pathImg = os.path.join(DIR_THUMBS, thumbfile)
        renderImg = ImageTk.PhotoImage(file=pathImg)
        but = tkinter.Button(root, image=renderImg)
        but.pack(side='left')
        but.bind('<Button-1>', lambda event, thumbfile=thumbfile: showItem(thumbfile))
        links.append(renderImg)


createThumbs()
outputButtons()

root.mainloop()

我编写了剧本,只是流行书“Mark Lutz。Programming Python”的例子。但由于一些奇怪的原因,我的脚本不起作用。

没有明显错误,因为屏幕不是错误消息。但是在弹出窗口中没有显示(显示空白弹出窗口)

1 个答案:

答案 0 :(得分:3)

在窗口有机会显示之前,(稍大)图像被垃圾收集。 您需要在图像周围保留一个参考来显示它。我从here获得了解决方案,您的showItem函数可能如下所示:

def showItem(imgfile):
    print(imgfile)
    pathImg = os.path.join(DIR_IMGS, imgfile)
    print(pathImg)
    renderImg = ImageTk.PhotoImage(file=pathImg)
    popup = tkinter.Toplevel()
    button = tkinter.Button(popup, image=renderImg)
    button.image = renderImg
    button.pack()