欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > tkinter显示图片

tkinter显示图片

2025/5/26 4:50:02 来源:https://blog.csdn.net/summerriver1/article/details/140111764  浏览:    关键词:tkinter显示图片

tkinter显示图片

  • 效果
  • 代码解析
    • 打开和显示图像
  • 代码

效果

在这里插入图片描述

代码解析

打开和显示图像

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()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词