前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python tkinter pil 缩略图 脚本

python tkinter pil 缩略图 脚本

作者头像
用户5760343
发布2022-05-13 10:50:43
3770
发布2022-05-13 10:50:43
举报
文章被收录于专栏:sktj

""" display all images in a directory as thumbnail image buttons that display the full image when clicked; requires PIL for JPEGs and thumbnail image creation; to do: add scrolling if too many thumbs for window! """

import os, sys, math from tkinter import * from PIL import Image # <== required for thumbs from PIL.ImageTk import PhotoImage # <== required for JPEG display

def makeThumbs(imgdir, size=(100, 100), subdir='thumbs'): """ get thumbnail images for all images in a directory; for each image, create and save a new thumb, or load and return an existing thumb; makes thumb dir if needed; returns a list of (image filename, thumb image object); caller can also run listdir on thumb dir to load; on bad file types may raise IOError, or other; caveat: could also check file timestamps; """ thumbdir = os.path.join(imgdir, subdir) if not os.path.exists(thumbdir): os.mkdir(thumbdir)

代码语言:javascript
复制
thumbs = []
for imgfile in os.listdir(imgdir):
    thumbpath = os.path.join(thumbdir, imgfile)
    if os.path.exists(thumbpath):
        thumbobj = Image.open(thumbpath)            # use already created
        thumbs.append((imgfile, thumbobj))
    else:
        print('making', thumbpath)
        imgpath = os.path.join(imgdir, imgfile)
        try:
            imgobj = Image.open(imgpath)            # make new thumb
            imgobj.thumbnail(size, Image.ANTIALIAS) # best downsize filter
            imgobj.save(thumbpath)                  # type via ext or passed
            thumbs.append((imgfile, imgobj))
        except:                                     # not always IOError
            print("Skipping: ", imgpath)
return thumbs

class ViewOne(Toplevel): """ open a single image in a pop-up window when created; photoimage object must be saved: images are erased if object is reclaimed; """ def init(self, imgdir, imgfile): Toplevel.init(self) self.title(imgfile) imgpath = os.path.join(imgdir, imgfile) imgobj = PhotoImage(file=imgpath) Label(self, image=imgobj).pack() print(imgpath, imgobj.width(), imgobj.height()) # size in pixels self.savephoto = imgobj # keep reference on me

def viewer(imgdir, kind=Toplevel, cols=None): """ make thumb links window for an image directory: one thumb button per image; use kind=Tk to show in main app window, or Frame container (pack); imgfile differs per loop: must save with a default; photoimage objs must be saved: erased if reclaimed; packed row frames (versus grids, fixed-sizes, canvas); """ win = kind() win.title('Viewer: ' + imgdir) quit = Button(win, text='Quit', command=win.quit, bg='beige') # pack first quit.pack(fill=X, side=BOTTOM) # so clip last thumbs = makeThumbs(imgdir) if not cols: cols = int(math.ceil(math.sqrt(len(thumbs)))) # fixed or N x N

代码语言:javascript
复制
savephotos = []
while thumbs:
    thumbsrow, thumbs = thumbs[:cols], thumbs[cols:]
    row = Frame(win)
    row.pack(fill=BOTH)
    for (imgfile, imgobj) in thumbsrow:
        photo   = PhotoImage(imgobj)
        link    = Button(row, image=photo)
        handler = lambda savefile=imgfile: ViewOne(imgdir, savefile)
        link.config(command=handler)
        link.pack(side=LEFT, expand=YES)
        savephotos.append(photo)
return win, savephotos

if name == 'main': imgdir = (len(sys.argv) > 1 and sys.argv[1]) or 'images' main, save = viewer(imgdir, kind=Tk) main.mainloop()

不保存缩略图

""" same, but make thumb images in memory without saving to or loading from files: seems just as fast for small directories, but saving to files makes startup much quicker for large image collections; saving may be needed in some apps (web pages) """

import os, sys from PIL import Image from tkinter import Tk import viewer_thumbs

def makeThumbs(imgdir, size=(100, 100), subdir='thumbs'): """ create thumbs in memory but don't cache to files """ thumbs = [] for imgfile in os.listdir(imgdir): imgpath = os.path.join(imgdir, imgfile) try: imgobj = Image.open(imgpath) # make new thumb imgobj.thumbnail(size) thumbs.append((imgfile, imgobj)) except: print("Skipping: ", imgpath) return thumbs

if name == 'main': imgdir = (len(sys.argv) > 1 and sys.argv[1]) or 'images' viewer_thumbs.makeThumbs = makeThumbs main, save = viewer_thumbs.viewer(imgdir, kind=Tk) main.mainloop()

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 不保存缩略图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档