将图像适配到CtkLabel中

编程语言 2026-07-08

我有一个CTkFrame,在其内部有一个CTkLabel,定义如下:

self.info_frame = ctk.CTkFrame(self, corner_radius=12)
self.info_frame.grid(
    row=1, column=0, padx=20,
    pady=(0, 10), sticky="ew")

self.info_frame.grid_columnconfigure(0, weight=0)
self.info_frame.grid_columnconfigure(1, weight=1)

self.lbl_thumbnail = ctk.CTkLabel(
    self.info_frame,
    text="[Thumbnail]",
    corner_radius=12,
    width=272,
    height=153,
    fg_color="gray20")
self.lbl_thumbnail.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")

在程序的后续阶段,将图像写入 self.lbl_thumbnail,文本会变成 "",因此唯一可见的将是图像。 下面是实现方式:

def _build_thumbnail_image(self, image_data):
    image = image_data.convert("RGBA")
    image = ImageOps.fit(
        image,
        (272, 153),
        method=Image.Resampling.LANCZOS,
        centering=(0.5, 0.5)
    )

    mask = Image.new("L", (272, 153), 0)
    mask_draw = ImageDraw.Draw(mask)
    mask_draw.rounded_rectangle(
        (0, 0, 272 - 1, 153 - 1),
        radius=12,
        fill=255
    )
    image.putalpha(mask)

    return ctk.CTkImage(
        light_image=image,
        dark_image=image,
        size=(272, 153)
    )

最后我编辑 self.lbl_thumbnail

thumb_bytes = meta['thumbnail_bytes']

if thumb_bytes:
    try:
        img_data = Image.open(BytesIO(thumb_bytes))

        self.thumbnail_image = self._build_thumbnail_image(img_data)
        self.lbl_thumbnail.configure(image=self.thumbnail_image, text="")
    except Exception as e:
        print(f"Warning: Failed to process thumbnail. {e}")
        self.lbl_thumbnail.configure(text="[Image Load Failed]", image=None)
else:
    self.lbl_thumbnail.configure(text="[No Thumbnail]", image=None)

问题在于,并不是把一个带圆角裁剪的图像正确地贴到尺寸为272x153的指定标签上,从而呈现出一张视觉上更美观的图像,而是得到一个标签对象,在缩略图的左、右两侧拉伸并出现黑条:

reproduced image

有人能否给我指引如何修复?

编辑:更新了图片

解决方案

我通过重新定义 self.lbl_thumbnail 解决了问题,现在我有

thumb_bytes = meta['thumbnail_bytes']

if thumb_bytes:
    try:
        img_data = Image.open(BytesIO(thumb_bytes))

        self.thumbnail_image = self._build_thumbnail_image(img_data)
        self.lbl_thumbnail = ctk.CTkLabel(
            self.info_frame,
            text="",
            image=self.thumbnail_image,
            width=272,
            height=153)
        self.lbl_thumbnail.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
    except Exception as e:
        print(f"Warning: Failed to process thumbnail. {e}")
        self.lbl_thumbnail.configure(text="[Image Load Failed]", image=None, corner_radius=12, fg_color="gray20")
else:
    self.lbl_thumbnail.configure(text="[No Thumbnail]", image=None, corner_radius=12, fg_color="gray20")
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章