怎么做交易猫钓鱼网站,网站优化的前景,邢台市第三医院,手术室专科建设网站tkinter显示图片 效果代码解析打开和显示图像 代码 效果 代码解析
打开和显示图像
def open_image():file_path filedialog.askopenfilename(title选择图片, filetypes((PNG文件, *.png), (JPEG文件, *.jpg;*.jpeg 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(imageimg_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(imageimg_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(imageimg_tk)img_label.image img_tk # 防止垃圾回收root tk.Tk()
root.title(图片显示示例)open_button tk.Button(root, text打开图片, commandopen_image)
open_button.pack(pady20)img_label tk.Label(root)
img_label.pack(pady20)root.mainloop()