我也写了一个,大家可以研究一下。
[Python] 纯文本查看 复制代码 import os
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
class ImageConverterApp:
def __init__(self, master):
self.master = master
master.title("批量WebP文件格式转换工具")
self.input_directory = ""
self.output_directory = ""
# 选择输入目录按钮
self.select_input_button = tk.Button(master, text="选择输入目录", command=self.select_input_dir)
self.select_input_button.pack()
# 选择格式标签
self.format_label = tk.Label(master, text="请选择目标格式:")
self.format_label.pack()
# 选择格式
self.format_var = tk.StringVar(master)
self.format_var.set(".png") # 默认转换为PNG
self.format_options = [".png", ".jpeg", ".gif"] # 可选格式
self.format_dropdown = tk.OptionMenu(master, self.format_var, *self.format_options)
self.format_dropdown.pack()
# 选择输出目录按钮
self.output_label = tk.Label(master, text="请选择输出目录:")
self.output_label.pack()
self.output_button = tk.Button(master, text="选择输出目录", command=self.select_output_directory)
self.output_button.pack()
# 转换按钮
self.convert_button = tk.Button(master, text="开始批量转换", command=self.convert)
self.convert_button.pack()
def select_input_dir(self):
self.input_directory = filedialog.askdirectory()
def select_output_directory(self):
self.output_directory = filedialog.askdirectory()
def convert(self):
if not self.input_directory:
self.show_message("请选择输入目录!")
return
if not self.output_directory:
self.show_message("请选择输出目录!")
return
output_format = self.format_var.get()
try:
# 获取输入目录中的所有WebP文件
webp_files = [f for f in os.listdir(self.input_directory) if f.endswith(".webp")]
if not webp_files:
self.show_message("输入目录中不存在WebP文件!")
return
# 遍历并转换每个WebP文件
for webp_file in webp_files:
input_file_path = os.path.join(self.input_directory, webp_file)
output_file = os.path.join(self.output_directory, os.path.splitext(webp_file)[0] + output_format)
with Image.open(input_file_path) as img:
img.save(output_file)
self.show_message("批量转换完成!")
except Exception as e:
self.show_message("转换失败:{}".format(str(e)))
def show_message(self, msg):
messagebox.showinfo("提示", msg)
def main():
root = tk.Tk()
app = ImageConverterApp(root)
root.mainloop()
if __name__ == "__main__":
main()
|