好友
阅读权限10
听众
最后登录1970-1-1
|
本帖最后由 52xiaosage 于 2024-11-28 23:44 编辑
有很多伙伴需要源代码,本着互相学习,相互帮助,相互贡献,我把源码奉献出来
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, UnidentifiedImageError
import os
from tkinterdnd2 import TkinterDnD, DND_FILES
import threading
VALID_EXTENSIONS = (".png", ".jpg", ".jpeg", ".bmp")
ICO_SIZES = [(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
class IconConverterApp:
def __init__(self, root):
self.root = root
self.root.title("批量图片转换ICO工具")
self.input_image_paths = [] # 存储多个图片文件路径
self.success_files = [] # 成功转换的文件
self.failed_files = [] # 失败的文件
self.output_folder = None # 默认输出文件夹为空
# 创建界面组件
self.description = tk.Label(root, text="将图片拖拽到窗口进行转换\n或点击区域选择图片", font=("Arial", 12))
self.description.pack(padx=10, pady=10)
# 输出路径提示
self.info_frame = tk.Frame(root)
self.info_frame.pack(padx=10, pady=5)
self.info_label = tk.Label(self.info_frame, text="文件默认保存到源文件夹,若需要自定义保存位置,", font=("Arial", 10), fg="gray")
self.info_label.pack(side="left")
# 解决文字不整齐的问题,调整按钮
self.output_button = tk.Button(self.info_frame, text="请点击更换保存位置", command=self.choose_output_folder, font=("Arial", 10, "bold"))
self.output_button.pack(side="left", padx=5, pady=5)
# 拖拽区域
self.drag_area_button = tk.Label(root, text="拖拽图片文件到此区域或点击选择文件", width=50, height=10, relief="solid", bg="#d1c4e9", fg="blue", font=("Arial", 12))
self.drag_area_button.pack(padx=10, pady=20)
root.drop_target_register(DND_FILES)
root.dnd_bind('<<Drop>>', self.on_drop)
self.drag_area_button.bind("<Button-1>", self.choose_files)
# 按钮区域
button_frame = tk.Frame(root)
button_frame.pack(pady=10)
self.export_button = tk.Button(button_frame, text="立即转换", command=self.start_conversion, width=15, height=2, font=("Arial", 14, "bold"), bg="orange", fg="white")
self.export_button.grid(row=0, column=1, padx=5)
def on_drop(self, event):
"""处理拖放事件"""
raw_paths = event.data.strip('{}').split('} {')
self.input_image_paths = [os.path.normpath(path) for path in raw_paths if path.lower().endswith(VALID_EXTENSIONS)]
if self.input_image_paths:
self.drag_area_button.config(text=f"已拖拽 {len(self.input_image_paths)} 个文件")
else:
messagebox.showerror("错误", "仅支持图片文件类型!")
def choose_files(self, event=None):
"""手动选择多个图片文件"""
file_paths = filedialog.askopenfilenames(title="选择图片文件", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.bmp")])
if file_paths:
self.input_image_paths = list(file_paths)
self.drag_area_button.config(text=f"已选择 {len(self.input_image_paths)} 个文件")
def choose_output_folder(self):
"""选择输出文件夹"""
folder = filedialog.askdirectory(title="选择输出文件夹")
if folder:
self.output_folder = folder
self.output_button.config(text="输出文件夹已选择", bg="#90EE90")
def convert_to_ico(self, input_image_path, output_ico_path):
"""根据图片尺寸生成 ICO 文件"""
try:
img = Image.open(input_image_path)
valid_sizes = [(w, h) for w, h in ICO_SIZES if w <= img.width and h <= img.height]
if not valid_sizes:
return f"图片 {os.path.basename(input_image_path)} 尺寸太小,无法生成图标"
img.save(output_ico_path, format='ICO', sizes=valid_sizes)
return True
except UnidentifiedImageError:
return "无法识别的图片格式"
except Exception as e:
return str(e)
def export_ico(self, input_image_path):
"""执行转换操作,单个文件的转换"""
if not self.output_folder:
self.output_folder = os.path.dirname(self.input_image_paths[0]) # 默认保存到第一个文件所在目录
base_name = os.path.splitext(os.path.basename(input_image_path))[0]
output_ico_path = os.path.join(self.output_folder, f"{base_name}.ico")
if os.path.exists(output_ico_path):
overwrite = messagebox.askyesno("覆盖确认", f"{output_ico_path} 已存在,是否覆盖?")
if not overwrite:
return
result = self.convert_to_ico(input_image_path, output_ico_path)
if result == True:
self.success_files.append(f"{base_name}.ico")
else:
self.failed_files.append(f"{base_name}: {result}")
def export_all_icos(self):
"""批量转换操作"""
self.success_files.clear()
self.failed_files.clear()
for input_image_path in self.input_image_paths:
self.export_ico(input_image_path)
success_msg = f"成功转换的文件:\n" + "\n".join(self.success_files) if self.success_files else "没有文件成功转换。"
failed_msg = f"\n失败的文件:\n" + "\n".join(self.failed_files) if self.failed_files else ""
messagebox.showinfo("转换结果", success_msg + failed_msg)
def start_conversion(self):
"""使用多线程避免界面卡顿"""
thread = threading.Thread(target=self.export_all_icos)
thread.start()
# 启动 GUI
root = TkinterDnD.Tk()
app = IconConverterApp(root)
root.mainloop()
|
免费评分
-
参与人数 1 | 吾爱币 +1 |
热心值 +1 |
收起
理由
|
rset
| + 1 |
+ 1 |
感谢发布原创作品,吾爱破解论坛因你更精彩! |
查看全部评分
|