当你点击缩略图来显示图像时?

2024-03-28 13:04:44 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮忙修改脚本。在

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

马克·卢蒂写了一本很受欢迎的剧本。编程Python”。但由于某些奇怪的原因,我的剧本不起作用。在

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


Tags: pathimportostkinterdefdirrootthumbs
1条回答
网友
1楼 · 发布于 2024-03-28 13:04:44

在窗口有机会显示图像之前(有点大)被垃圾回收。 您需要在图像周围保留一个引用来显示它。我已经从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()   

相关问题 更多 >