Thought this was going to be easy, but it took a good minute to figure out. You need a container for all the images you .open()
#! /usr/bin/python3
import os
import glob
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
from PIL import ImageTk, Image
## ImportError: cannot import name 'ImageTk' from 'PIL'
## pip3 install --upgrade --force-reinstall pillow
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
title = 'PyThumbs'
root = tk .Tk() ; root .title( title )
root .bind( '<Escape>', lambda e: root .destroy() )
root .attributes( '-zoomed', True )
root .update_idletasks()
rootw, rooth = root .winfo_width(), root .winfo_height()
home = os .environ['HOME']
folder_selected = filedialog .askdirectory( initialdir = home, title = 'Select Folder' )
imagenames = []
for filename in glob .glob( str( folder_selected ) +'/*.jpg' ):
imagenames .append( filename )
cols, rows = 4, 3
cellw, cellh = rootw //cols, rooth //rows
texth = cellh //12
photow, photoh = cellw, cellh -texth
images = []
for col in range( cols ):
images .append( [] )
for row in range( rows ):
images[ col ] .append( [] )
def createIMG( c, r, i ):
fullpath = imagenames[ i ]
directory, filename = os .path .split( fullpath )
name, extension = os .path .splitext( filename )
print( c, r, i, fullpath )
img = Image .open( fullpath )
ratio = min( photow /img .width, photoh/ img .height )
thumb = img .resize( ( int( img .width *ratio ), int( img .height *ratio ) ) )
images[ c ][ r ] = ImageTk .PhotoImage( image = thumb )
cell = ttk .Button( root, name = f'{c}cell{r}', image = images[ c ][ r ] )
cell .place( x = c *cellw, y = r *cellh, width = cellw, height = photoh )
text = tk .Label( root, name = f'{c}text{r}', text = name[:20] )
text .place( x = c *cellw, y = (r +1) *cellh -texth, width = cellw, height = texth )
index = 0
for col in range( cols ):
for row in range( rows ):
try:
createIMG( col, row, index )
## t = createIMG( col, row, index )
## threading .Thread( target = t ) .start()
except: pass
index += 1
root .mainloop()