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