【问题标题】:tk.Label with image not resizing correctlytk.Label 与图像未正确调整大小
【发布时间】:2019-07-31 14:04:59
【问题描述】:

我有以下 tkinter 示例:

from PIL import Image, ImageTk
import tkinter as tk

root = tk.Toplevel()

container_frame = tk.Frame(master=root)
container_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
top_frame = tk.Frame(container_frame, background='red')
middle_frame = tk.Frame(container_frame, background='green')
bottom_frame = tk.Frame(container_frame, background='blue')

top_frame.grid(row=0, column=0, sticky='NSEW')
middle_frame.grid(row=1, column=0, sticky='NSEW')
bottom_frame.grid(row=2, column=0, sticky='NSEW')
container_frame.grid_columnconfigure(0, weight=1)
container_frame.grid_rowconfigure(0, weight=1, uniform='container_frame')
container_frame.grid_rowconfigure(1, weight=7, uniform='container_frame')
container_frame.grid_rowconfigure(2, weight=2, uniform='container_frame')

image = Image.open('some_image.png')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(top_frame, image=photo_image, background='yellow', anchor='w')
label.image = photo_image
label.pack(expand=1, side='left')

root.geometry('1280x720')
root.mainloop()

不幸的是,label 中的image 没有被缩小以正确适应top_frame这是为什么? 此外,当我调整窗口大小时,label(因此image)根本不会调整大小。再说一次,这是为什么?

感谢您的帮助。

【问题讨论】:

  • 标签从不调整图像大小 - 你必须自己做。您必须使用PIL 生成具有新尺寸的图像。
  • 示例如何使用bind('<Configure>') 在图像改变大小时运行函数 - 此函数使用 PIL 生成新大小的图像:furas/python-examples/tkinter/resize-image-in-background/

标签: python python-3.x image tkinter label


【解决方案1】:

不幸的是,标签内的图像没有被缩小以正确适应 top_frame。为什么是这样?

这是因为 tkinter 不是这样工作的。它不会自动为您放大和缩小图像。它会扩大和缩小标签,但不会扩大和缩小里面的图像。您必须使用 Pillow 等外部库来编写代码。

此外,当我调整窗口大小时,标签(以及图像)根本不会调整大小。再说一遍,这是为什么呢?

正如我之前所写,图像永远不会改变。至于为什么标签不改变,那是因为你已经将它配置为不改变。

考虑这行代码:

label.pack(expand=1, side='left')

expand 选项表示任何额外的空间都被赋予标签,tkinter 就是这样做的。但是,通过将 fill 选项保留为默认值,您已指示 tkinter扩展标签以填充分配给它的空间。

如果您希望标签增长,请添加fill='both'

【讨论】:

  • 感谢您的详细回答——帮助很大。你知道算法“增长和缩小”图像的良好链接吗?
  • @alex_lewis:这个问题涉及窗口的背景,但同样的技术也适用于标签:stackoverflow.com/questions/24061099/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
相关资源
最近更新 更多