使用for loop、tkinter显示多个图像

2024-06-28 15:22:10 发布

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

我想在窗口的目录中显示多个图像

但根据这段代码,一次只能显示一个图像

这是我的密码:

base = Tk()
base.geometry('1000x1000')

folder_selected = filedialog.askdirectory()
txtfiles = []
for file in glob.glob(str(folder_selected) + "/*.jpg"):
    txtfiles.append(file)
a = 10

def createIMG():
    global a, img
    for location in txtfiles:
        n = Label(base, text='asd')
        n.place(x=a, y=10)

        img = Image.open(location)
        img = img.resize((250, 250))
        img = ImageTk.PhotoImage(img)
        panel = Label(base, image=img)
        panel.place(x=a,y=10)
        a = a + 200

createIMG()
# threading.Thread(target=createIMG).start()

mainloop()

Tags: in图像imgforbaseplacelocationfolder
1条回答
网友
1楼 · 发布于 2024-06-28 15:22:10

我以为这很容易,但花了很长时间才弄明白。您需要一个容器来存放所有需要的图像.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()

相关问题 更多 >