【问题标题】:Tkinter resizing images in labels arranged in a gridTkinter 调整以网格排列的标签中的图像大小
【发布时间】:2020-12-04 11:44:42
【问题描述】:

首先,我对 Tkinter 完全陌生,正在尝试制作一个 Raspberry Pi 媒体播放器...

我抓取 USB 驱动器上所有 .mp4 文件的目录,并使用 PIL 将视频的缩略图放入 3x3 的标签网格中,网格位于框架内(代码中的 frame2)。

现在,由于缩略图大小不同,标签的大小也不一致。此外,仅显示较大缩略图的右上角部分,而不是整个图像。

如何以网格形式缩放缩略图并将其放入大小一致的标签中?

这是我的代码的一部分(它非常大,所以我尝试只包含相关部分):

import tkinter as tk

from subprocess import Popen
from time import sleep
import os
from random import randint

import imageio
from PIL import ImageTk, Image
from pathlib import Path

#putting 100th frame of video with 'path' into the label
def pack_thumbnail(path, label):
    #this is probably not a good way to do this
    video = imageio.get_reader(path)
    for i in range(100):
        try:
            image = video.get_next_data()
        except:
            video.close()
            break
    frame_image = ImageTk.PhotoImage(Image.fromarray(image))
    label.config(image=frame_image)
    label.image = frame_image

window = tk.Tk()
window.attributes("-fullscreen", True)

frame1 = tk.Frame(master=window, width=200, height=100, bg="white")
frame1.pack(fill=tk.Y, side=tk.LEFT)
#frame2 contains the grid of labels
frame2 = tk.Frame()

for i in range(3):
    frame2.columnconfigure(i, weight=1, minsize=75)
    frame2.rowconfigure(i, weight=1, minsize=50)
    
    for j in range(0, 3):
        frame = tk.Frame(master=frame2, relief=tk.RAISED, borderwidth=1)
        frame.grid(row=i, column=j, padx=5, pady=5)

        #path to video to get thumbnail (i only have 3 videos so i randomize it)
        vid_path=f"/media/pi/{os.listdir('/media/pi/')[0]}/{folder_name}/{videos[randint(0, 2)]}"

        label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")
        pack_thumbnail(vid_path, label)
        label.pack(padx=5, pady=5)
frame2.pack()

window.bind("<Escape>", lambda x: window.destroy())
window.mainloop()

【问题讨论】:

    标签: python-3.x tkinter python-imaging-library


    【解决方案1】:

    您可以使用Image.thumbnail()调整图片大小:

    # putting 100th frame of video with 'path' into the label
    def pack_thumbnail(path, label):
        with imageio.get_reader(path) as video:
            image = video.get_data(100)  # use get_date() instead of get_next_data()
        w, h = 200, 200  # thumbnail size
        image = Image.fromarray(image)
        image.thumbnail((w, h)) # resize the image
        frame_image = ImageTk.PhotoImage(image)
        label.config(image=frame_image, width=w, height=h)
        label.image = frame_image
    

    【讨论】:

    • 图片现在适合标签了,谢谢! w, h 是像素还是文本单位的缩略图大小?
    • 它们以像素为单位。
    猜你喜欢
    • 2013-06-25
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    相关资源
    最近更新 更多