2014-02-11 56 views
0

请帮忙修复脚本。因为一旦你点击缩略图来显示图像?

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”的例子。但由于一些奇怪的原因,我的脚本不起作用。

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

回答

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