2014-02-11 55 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()