Python三个方法(直接拿来用)给Tkinter的Label设置图片

本文介绍了三种方式将图片设置到Tkinter窗口中:通过PIL模块直接调整大小,原生tkinter写法创建Label,以及OpenCV与Tkinter结合。方法包括设置img_path,img_size选项,并提供了详细示例和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:从路径直接设置,需要 PIL.Image 模块

此函数将图片文件 img_path 设置到 tkinter 窗口的 tk_label 上。

可以用二元组 (height, width) 指定把图片缩放后再放置

需要的包:

from tkinter import *

from PIL import Image
def set_image_to_tk(tk_label, img_path, img_size=None):
    img_open = Image.open(img_path)
    if img_size is not None:
        height, width = img_size
        img_h, img_w = img_open.size

        if img_w > width:
            size = (width, int(height * img_w / img_h))
            img_open = img_open.resize(size, Image.ANTIALIAS)

        elif img_h > height:
            size = (int(width * img_h / img_w), height)
            img_open = img_open.resize(size, Image.ANTIALIAS)

    img = ImageTk.PhotoImage(img_open)
    tk_label.config(image=img)
    tk_label.image = img

参数类型

tk_label        tkinter.Label
img_pathstr
img_sizeTuple[int, int]

用法

label = Label(self.root)
set_image_to_tk(label, 'image.jpg')
label.pack()

注意:导入包 from PIL import Image 一定要在 from tkinter import * 后面,否则 Image 类是错误的 

方法二:原生 tkinter 写法

需要的包:

from tkinter import *

函数 give_label_with_picture 直接返回一个 Label,支持所有 Label 操作,用法和 Label 一样

def give_label_with_picture(master, image) -> Label:
    """ 给一个包含图片的 Label,可以直接布局 """
    photo = PhotoImage(file=image)
    lab = Label(master)
    lab.config(image=photo)
    lab.image = photo
    return lab

用法:

give_label_with_picture(self.root, '/path/to/image').pack()

方法三:从 openCV 直接设置

需要的包:

from tkinter import *

from PIL import Image

import cv2
def set_opencv_image_to_tk(self, label, cv2_img, img_size=None):
    current_image = Image.fromarray(cv2_img)
    if img_size is not None:
        current_image = current_image.resize(img_size)
    imgtk = ImageTk.PhotoImage(image=current_image)
    label.imgtk = imgtk
    label.config(image=imgtk)

其中 cv2_img 是一个 np.array 对象,用法和方法一一样

### 如何在Python TkinterLabel控件中显示图片 要在Python Tkinter中的`Label`控件上显示图片,通常需要借助`PhotoImage`类来加载图像文件并将其分配给`Label`的小部件属性。以下是实现这一目标的具体方法: #### 使用 `PhotoImage` 加载图像 `PhotoImage` 是 Tkinter 提供的一个用于处理图像的类,它能够读取 GIF 和 PGM/PPM 格式的图像[^1]。如果要使用其他格式(如 PNG 或 JPEG),则需引入外部库 PIL (Pillow) 来扩展支持。 ```python from tkinter import * from PIL import Image, ImageTk # 导入 Pillow 库以支持更多图像格式 root = Tk() root.title("Displaying Images") # 创建 PhotoImage 对象 image_path = "example.png" # 替换为实际路径 img = Image.open(image_path) # 打开图像文件 photo = ImageTk.PhotoImage(img) # 将图像绑定到 Label 控件 label = Label(root, image=photo) label.image = photo # 防止垃圾回收机制清除图像对象 label.pack() root.mainloop() ``` 上述代码展示了如何通过 `ImageTk.PhotoImage` 方法加载 PNG 图像,并将其设置为 `Label` 的 `image` 属性值[^2]。 #### 关键注意事项 - **保持引用**:为了防止 Python 的垃圾收集器过早释放图像资源,在将图像赋值给 `Label` 后,应显式保存该图像的对象引用。 - **跨平台兼容性**:虽然 Tkinter 基于 Tcl/Tk 实现,但在不同操作系统上的表现可能略有差异。因此建议测试程序运行环境的一致性。 #### 支持多种图像格式的方法 由于原生 `PhotoImage` 只能解析有限几种图像格式,推荐利用第三方模块 Pillow 进行转换操作。此方式不仅简化了复杂流程还增强了应用灵活性。 ```python pip install pillow # 安装前先确认环境中已安装 pip 工具 ``` 以上命令可完成对所需依赖项的安装过程以便顺利执行前述脚本片段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值