如何在Python脚本中校验图片文件扩展名并仅接受合法格式?
改进后的图片转ICO工具脚本
以下是修改后的完整代码,支持你指定的所有图片格式校验与转换:
from tkinter import * from tkinter import filedialog as fd from PIL import Image root = Tk() root.geometry("400x400") root.title("Image_Conversion_App") # 定义支持的图片扩展名集合 SUPPORTED_FORMATS = {"JPG", "JPEG", "jpg", "jpeg", "png", "PNG", "bmp", "BMP", "gif", "GIF", "tiff", "TIFF", "webp", "WEBP"} # 创建全局错误提示标签,复用避免重复创建 error_label = Label(root, text="", width=20, fg="red", font=("bold", 15)) error_label.place(x=80, y=280) def image_to_ico(): # 打开文件选择对话框,直接过滤支持的格式 filename = fd.askopenfilename( filetypes=[("Supported Images", "*.jpg *.jpeg *.png *.bmp *.gif *.tiff *.webp"), ("All Files", "*.*")] ) if not filename: return # 用户取消选择 # 获取文件扩展名并统一转为大写判断 ext = filename.split(".")[-1].upper() if ext in [fmt.upper() for fmt in SUPPORTED_FORMATS]: # 基于原文件名生成ICO文件名,避免覆盖 ico_filename = f"{filename.rsplit('.', 1)[0]}.ico" try: Image.open(filename).save(ico_filename) error_label.config(text="转换成功!", fg="green") except Exception as e: error_label.config(text=f"转换失败: {str(e)}", fg="red") else: error_label.config(text="格式不支持!", fg="red") Label_1 = Label(root, text="Browse A File", width=20, font=("bold", 15)) Label_1.place(x=80, y=80) Label_3 = Label(root, text="</Eddy/> \n", width=80, font=("bold", 8)) Label_3.place(x=10, y=365) # 合并为一个通用按钮,支持所有格式转换 Button(root, text="图片转ICO", width=20, height=2, bg="brown", fg="white", command=image_to_ico).place(x=120, y=160) root.mainloop()
关键修改说明
- 统一格式校验:定义
SUPPORTED_FORMATS集合包含所有允许的扩展名,通过转换为大写统一判断逻辑,避免大小写遗漏 - 简化功能函数:合并原有的两个转换函数为
image_to_ico,减少重复代码,同时支持所有指定格式 - 优化文件选择体验:在
askopenfilename中添加filetypes参数,用户打开对话框时默认只显示支持的图片格式,减少误选 - 复用提示标签:提前创建全局错误提示标签,通过
config方法更新内容,避免多次创建Label导致界面重叠 - 友好的输出命名:基于原文件名生成ICO文件,避免固定名称覆盖之前的转换结果
- 异常捕获:添加转换过程的异常捕获,提示具体错误原因,提升容错性
内容的提问来源于stack exchange,提问作者Eddy Yahwin
相关产品推荐
相关产品推荐

