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

方法一:从路径直接设置,需要 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 对象,用法和方法一一样

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值