-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
444 lines (365 loc) · 16.5 KB
/
Copy pathmain.py
File metadata and controls
444 lines (365 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
"""
图片裁剪工具 - Windows 11 风格桌面应用 (最终版)
- 图标按文档统一
- 已移除撤销功能
- 删除确认弹窗居中
- Spinbox 字体缩小
- 裁切像素输入框为空时自动补0
"""
import os
import sys
import traceback
from pathlib import Path
from tkinter import filedialog, messagebox, StringVar, IntVar, BooleanVar
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
DND_AVAILABLE = True
except ImportError:
DND_AVAILABLE = False
print("警告:tkinterdnd2 未安装,拖拽功能将被禁用。可通过 pip install tkinterdnd2 安装。")
import tkinter as tk
from tkinter import ttk, font as tkfont
try:
import sv_ttk
SV_TTK_AVAILABLE = True
except ImportError:
SV_TTK_AVAILABLE = False
print("警告:sv_ttk 未安装,将使用默认 ttk 主题。可通过 pip install sv_ttk 安装。")
try:
from PIL import Image
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
print("错误:Pillow 未安装,请通过 pip install Pillow 安装。程序将无法正常运行。")
sys.exit(1)
SUPPORTED_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp')
class SkipConfirmDialog(tk.Toplevel):
"""居中显示的确认对话框,带“下次不再提示”复选框"""
def __init__(self, parent, title, message, skip_var: BooleanVar):
super().__init__(parent)
self.title(title)
self.result = False
self.skip_var = skip_var
self.resizable(False, False)
self.transient(parent)
self.grab_set()
frame = ttk.Frame(self, padding=15)
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text=message, wraplength=300).pack(pady=(0, 10))
self.skip_check = ttk.Checkbutton(frame, text="下次不再提示", variable=self.skip_var)
self.skip_check.pack(anchor="w", pady=(0, 10))
btn_frame = ttk.Frame(frame)
btn_frame.pack(fill=tk.X, pady=(5, 0))
ttk.Button(btn_frame, text="确定", command=self._ok).pack(side=tk.RIGHT, padx=5)
ttk.Button(btn_frame, text="取消", command=self._cancel).pack(side=tk.RIGHT)
# 计算窗口位置使其居中于父窗口
self.update_idletasks()
parent_x = parent.winfo_rootx()
parent_y = parent.winfo_rooty()
parent_w = parent.winfo_width()
parent_h = parent.winfo_height()
self_w = self.winfo_width()
self_h = self.winfo_height()
x = parent_x + (parent_w - self_w) // 2
y = parent_y + (parent_h - self_h) // 2
self.geometry(f"+{x}+{y}")
self.protocol("WM_DELETE_WINDOW", self._cancel)
self.wait_window(self)
def _ok(self):
self.result = True
self.destroy()
def _cancel(self):
self.result = False
self.destroy()
class ImageCropApp:
def __init__(self, root):
self.root = root
self.root.title("批量图片裁剪工具 By muxia0396")
self.root.geometry("1000x680")
self.root.minsize(800, 500)
try:
self.root.iconbitmap("assets/icon.ico")
except Exception:
pass
self.files: list[Path] = []
# 裁切变量
self.crop_top = IntVar(value=0)
self.crop_bottom = IntVar(value=0)
self.crop_left = IntVar(value=0)
self.crop_right = IntVar(value=0)
self.overwrite_var = BooleanVar(value=False)
self.status_text = StringVar(value="就绪")
# 删除确认跳过标志
self.skip_delete_confirm = BooleanVar(value=False)
# 设置 Sun Valley 主题
if SV_TTK_AVAILABLE:
sv_ttk.set_theme("light")
self.current_theme = "light"
else:
self.current_theme = "light"
# 配置小字体样式(用于 Spinbox)
style = ttk.Style()
style.configure("Small.TSpinbox", font=("Segoe UI", 9))
self._setup_ui()
self._refresh_file_list()
def _setup_ui(self):
self._create_toolbar()
self.paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
self.paned.pack(fill=tk.BOTH, expand=True, padx=10, pady=(5, 10))
control_frame = ttk.Frame(self.paned, width=300)
self.paned.add(control_frame, weight=0)
self._create_control_panel(control_frame)
list_frame = ttk.Frame(self.paned)
self.paned.add(list_frame, weight=1)
self._create_file_list_panel(list_frame)
self._create_status_bar()
def _create_toolbar(self):
toolbar = ttk.Frame(self.root, padding=(10, 10, 10, 0))
toolbar.pack(fill=tk.X)
left_btn_frame = ttk.Frame(toolbar)
left_btn_frame.pack(side=tk.LEFT)
# 图标统一:打开图片 -> ➕,添加文件夹 -> 📁
ttk.Button(left_btn_frame, text="📁 选择文件夹", command=self._add_folder_via_dialog).pack(
side=tk.LEFT, padx=(0, 5))
ttk.Button(left_btn_frame, text="➕ 添加文件", command=self._add_files_via_dialog).pack(
side=tk.LEFT, padx=(0, 5))
ttk.Button(left_btn_frame, text="❌ 清空列表", command=self._clear_file_list).pack(
side=tk.LEFT, padx=(0, 5))
right_btn_frame = ttk.Frame(toolbar)
right_btn_frame.pack(side=tk.RIGHT)
self.theme_btn = ttk.Button(right_btn_frame, text="🌙 暗黑模式", command=self._toggle_theme)
self.theme_btn.pack(side=tk.RIGHT, padx=(5, 0))
def _create_control_panel(self, parent):
canvas = tk.Canvas(parent, highlightthickness=0)
scrollbar = ttk.Scrollbar(parent, orient="vertical", command=canvas.yview)
self.control_frame_inner = ttk.Frame(canvas, padding=(10, 10))
self.control_frame_inner.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=self.control_frame_inner, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
def _on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
canvas.bind_all("<MouseWheel>", _on_mousewheel)
crop_group = ttk.LabelFrame(self.control_frame_inner, text="裁切设置 (像素)", padding=(10, 10))
crop_group.pack(fill=tk.X, pady=(0, 10))
# 输入验证:只允许非负整数
def validate_input(P):
if P == "":
return True
if P.isdigit():
return True
return False
vcmd = (self.root.register(validate_input), '%P')
labels_vars = [
("左", self.crop_top),
("右", self.crop_bottom),
("上", self.crop_left),
("下", self.crop_right),
]
for i, (label, var) in enumerate(labels_vars):
ttk.Label(crop_group, text=label).grid(row=i, column=0, sticky="w", pady=3)
s = ttk.Spinbox(crop_group, from_=0, to=9999, textvariable=var, width=7,
style="Small.TSpinbox", validate='key', validatecommand=vcmd)
s.grid(row=i, column=1, sticky="e", pady=3, padx=(10, 0))
# 焦点离开时:如果输入框为空则自动设为0
s.bind("<FocusOut>", lambda e, v=var, sb=s: v.set(0) if sb.get().strip() == "" else None)
ttk.Checkbutton(crop_group, text="覆盖原图 (⚠ 操作不可恢复)", variable=self.overwrite_var).grid(
row=4, column=0, columnspan=2, sticky="w", pady=(10, 0))
# 操作按钮组(已移除撤销)
action_group = ttk.LabelFrame(self.control_frame_inner, text="操作", padding=(10, 10))
action_group.pack(fill=tk.X, pady=(0, 10))
ttk.Button(action_group, text="📸 裁剪全部", command=self._crop_all).pack(fill=tk.X, pady=2)
preview_group = ttk.LabelFrame(self.control_frame_inner, text="文件统计", padding=(10, 10))
preview_group.pack(fill=tk.BOTH, expand=True)
self.preview_label = ttk.Label(preview_group, text="当前列表为空", anchor="center", relief="sunken")
self.preview_label.pack(fill=tk.BOTH, expand=True)
def _create_file_list_panel(self, parent):
columns = ("原文件名", "文件路径", "操作")
self.tree = ttk.Treeview(parent, columns=columns, show="headings", selectmode="none")
self.tree.heading("原文件名", text="原文件名", anchor="w")
self.tree.heading("文件路径", text="文件路径", anchor="w")
self.tree.heading("操作", text="", anchor="center")
self.tree.column("原文件名", width=200, minwidth=150)
self.tree.column("文件路径", width=250, minwidth=200)
self.tree.column("操作", width=40, minwidth=40, anchor="center")
tree_scroll = ttk.Scrollbar(parent, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=tree_scroll.set)
self.tree.pack(side="left", fill="both", expand=True)
tree_scroll.pack(side="right", fill="y")
self.tree.bind("<ButtonRelease-1>", self._on_tree_click)
if DND_AVAILABLE:
self.root.drop_target_register(DND_FILES)
self.root.dnd_bind('<<Drop>>', self._on_drop_files)
self.drag_hint = ttk.Label(parent, text="📥 拖拽图片或文件夹到此处",
foreground="gray", anchor="center")
self.drag_hint.place(relx=0.5, rely=0.5, anchor="center")
def _create_status_bar(self):
status_bar = ttk.Frame(self.root, relief="sunken", padding=(10, 5))
status_bar.pack(fill=tk.X, side=tk.BOTTOM)
ttk.Label(status_bar, textvariable=self.status_text, anchor="w").pack(side=tk.LEFT)
self.progress = ttk.Progressbar(status_bar, mode="indeterminate", length=150)
self.progress.pack(side=tk.RIGHT, padx=(10, 0))
# ---------- 文件管理 ----------
def _add_files(self, file_paths: list[str]):
added = 0
for fp in file_paths:
path = Path(fp)
if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS and path not in self.files:
self.files.append(path)
added += 1
if added:
self.status_text.set(f"就绪 - 已添加 {added} 个文件,共 {len(self.files)} 个")
return added
def _add_files_via_dialog(self):
files = filedialog.askopenfilenames(
title="选择图片文件",
filetypes=[("图片文件", "*" + ";*".join(SUPPORTED_EXTENSIONS))]
)
if files:
self._add_files(list(files))
self._refresh_file_list()
def _add_folder_via_dialog(self):
folder = filedialog.askdirectory(title="选择文件夹")
if folder:
folder_path = Path(folder)
img_files = []
for ext in SUPPORTED_EXTENSIONS:
img_files.extend(folder_path.rglob(f"*{ext}"))
self._add_files([str(f) for f in img_files])
self._refresh_file_list()
def _on_drop_files(self, event):
if not DND_AVAILABLE:
return
raw_data = self.root.tk.splitlist(event.data)
file_paths = []
for item in raw_data:
path = Path(item)
if path.is_dir():
for ext in SUPPORTED_EXTENSIONS:
file_paths.extend([str(p) for p in path.rglob(f"*{ext}")])
else:
file_paths.append(str(path))
self._add_files(file_paths)
self._refresh_file_list()
def _delete_file_by_path(self, file_path: Path):
if file_path in self.files:
self.files.remove(file_path)
self._refresh_file_list()
self.status_text.set(f"已从列表移除: {file_path.name}")
def _clear_file_list(self):
if not self.files:
return
if messagebox.askyesno("确认清空", "确定要清空所有文件吗?"):
self.files.clear()
self._refresh_file_list()
self.status_text.set("就绪 - 列表已清空")
def _refresh_file_list(self):
for item in self.tree.get_children():
self.tree.delete(item)
for file in self.files:
self.tree.insert("", tk.END, values=(file.name, str(file.parent), "✕"))
count = len(self.files)
self.preview_label.config(text="当前列表为空" if count == 0 else f"共 {count} 张图片")
self.status_text.set(f"就绪 - 共 {len(self.files)} 个文件")
# ---------- 列表删除(弹窗居中) ----------
def _on_tree_click(self, event):
region = self.tree.identify_region(event.x, event.y)
if region != "cell":
return
column = self.tree.identify_column(event.x)
row_id = self.tree.identify_row(event.y)
if column == "#3" and row_id:
values = self.tree.item(row_id, "values")
if values:
file_name = values[0]
file_dir = values[1]
file_path = Path(file_dir) / file_name
if self.skip_delete_confirm.get():
self._delete_file_by_path(file_path)
return
dialog = SkipConfirmDialog(
self.root,
"确认删除",
f"确定要从列表中移除 \"{file_name}\" 吗?\n(不会删除磁盘文件)",
self.skip_delete_confirm
)
if dialog.result:
self._delete_file_by_path(file_path)
# ---------- 裁剪核心 ----------
def _get_crop_box(self, img_width, img_height):
"""获取裁剪坐标(语义:上/下->左右,左/右->上下)"""
left = self.crop_top.get()
right = img_width - self.crop_bottom.get()
top = self.crop_left.get()
bottom = img_height - self.crop_right.get()
left = max(0, min(left, img_width))
right = max(left, min(right, img_width))
top = max(0, min(top, img_height))
bottom = max(top, min(bottom, img_height))
return (left, top, right, bottom)
def _crop_all(self):
if not self.files:
messagebox.showwarning("提示", "文件列表为空,请先添加图片。")
return
indices = list(range(len(self.files)))
self._process_crop(indices)
def _process_crop(self, indices: list[int]):
if not indices:
return
self.progress.start()
self.status_text.set("正在裁剪...")
self.root.update_idletasks()
try:
for idx in indices:
file_path = self.files[idx]
try:
with Image.open(file_path) as img:
w, h = img.size
box = self._get_crop_box(w, h)
cropped = img.crop(box)
if self.overwrite_var.get():
new_path = file_path
else:
stem = file_path.stem
suffix = file_path.suffix
new_path = file_path.with_name(f"{stem}_cropped{suffix}")
if new_path.exists() and not self.overwrite_var.get():
counter = 1
while new_path.exists():
new_path = file_path.with_name(f"{stem}_cropped_{counter}{suffix}")
counter += 1
cropped.save(new_path)
self.status_text.set(f"已裁剪: {file_path.name} -> {new_path.name}")
except Exception:
err = traceback.format_exc()
self.status_text.set(f"错误: {file_path.name} 裁剪失败")
print(err)
finally:
self.progress.stop()
self._refresh_file_list()
self.status_text.set(f"就绪 - 共 {len(self.files)} 个文件")
def _toggle_theme(self):
if not SV_TTK_AVAILABLE:
messagebox.showinfo("提示", "sv_ttk 未安装,无法切换主题。")
return
if self.current_theme == "light":
sv_ttk.set_theme("dark")
self.current_theme = "dark"
self.theme_btn.config(text="☀️ 浅色模式")
else:
sv_ttk.set_theme("light")
self.current_theme = "light"
self.theme_btn.config(text="🌙 暗黑模式")
def main():
if DND_AVAILABLE:
root = TkinterDnD.Tk()
else:
root = tk.Tk()
app = ImageCropApp(root)
root.mainloop()
if __name__ == "__main__":
main()