效果

代码解析
打开和显示图像
def open_image():file_path = filedialog.askopenfilename(title="选择图片", filetypes=(("PNG文件", "*.png"), ("JPEG文件", "*.jpg;*.jpeg"), ("所有文件", "*.*")))if file_path:img = Image.open(file_path)img = img.resize((300, 300), Image.Resampling.LANCZOS) img_tk = ImageTk.PhotoImage(img)img_label.config(image=img_tk)img_label.image = img_tk
- file_path =
filedialog.askopenfilename(…):打开一个文件选择对话框,让用户选择一个文件。title
参数设置对话框的标题,filetypes 参数用于过滤显示的文件类型(PNG 文件、JPEG 文件和所有文件)。 - if file_path::检查用户是否选择了文件。
- img = Image.open(file_path):使用 Pillow 库打开图像文件。
- img = img.resize((300, 300), Image.Resampling.LANCZOS):调整图像大小为
300x300 像素,使用 LANCZOS 作为重采样滤波器。 - img_tk = ImageTk.PhotoImage(img):将图像转换为 PhotoImage 对象,以便在 tkinter
中显示。 - img_label.config(image=img_tk) 和 img_label.image =
img_tk:更新标签以显示选中的图像,并存储 img_tk 对象以防止被垃圾回收。
代码
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTkdef open_image():file_path = filedialog.askopenfilename(title="选择图片", filetypes=(("PNG文件", "*.png"), ("JPEG文件", "*.jpg;*.jpeg"), ("所有文件", "*.*")))if file_path:img = Image.open(file_path)img = img.resize((300, 300), Image.Resampling.LANCZOS) img_tk = ImageTk.PhotoImage(img)img_label.config(image=img_tk)img_label.image = img_tk root = tk.Tk()
root.title("图片显示示例")open_button = tk.Button(root, text="打开图片", command=open_image)
open_button.pack(pady=20)img_label = tk.Label(root)
img_label.pack(pady=20)root.mainloop()