-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
1623 lines (1517 loc) · 57.4 KB
/
Copy pathapp.py
File metadata and controls
1623 lines (1517 loc) · 57.4 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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Perfect Pixel Studio — native Windows desktop interface."""
from __future__ import annotations
import ctypes
from pathlib import Path
import os
import queue
import sys
import threading
import tkinter as tk
from tkinter import colorchooser, filedialog, messagebox, ttk
try:
import winreg
except ImportError: # pragma: no cover - only used outside Windows
winreg = None
import numpy as np
from PIL import Image, ImageGrab, ImageOps, ImageTk
from tkinterdnd2 import COPY, DND_FILES, REFUSE_DROP, TkinterDnD
from perfect_pixel_core import (
ProcessResult,
ProcessSettings,
array_to_png_bytes,
create_result_zip,
process_image,
suggested_names,
)
APP_NAME = "Perfect Pixel"
APP_VERSION = "2.2"
UI_FONT = "Microsoft YaHei UI"
SUPPORTED_IMAGE_SUFFIXES = {
".png",
".jpg",
".jpeg",
".webp",
".gif",
".bmp",
".tif",
".tiff",
}
DARK_COLORS = {
"bg": "#0B1014",
"sidebar": "#0F161B",
"surface": "#121B21",
"surface_hover": "#18242B",
"surface_active": "#203139",
"preview": "#0A0E11",
"line": "#26343C",
"line_soft": "#1C282F",
"text": "#F2F7F7",
"text_soft": "#C8D2D6",
"muted": "#87969E",
"accent": "#42D7C2",
"accent_hover": "#64E5D2",
"accent_dark": "#082B28",
"error": "#FF8A80",
"checker_a": "#10171B",
"checker_b": "#182126",
}
LIGHT_COLORS = {
"bg": "#F5F7F6",
"sidebar": "#EEF2F1",
"surface": "#FFFFFF",
"surface_hover": "#E5ECEA",
"surface_active": "#D8F1EC",
"preview": "#E7ECEA",
"line": "#C3CECA",
"line_soft": "#DCE4E1",
"text": "#13201D",
"text_soft": "#344943",
"muted": "#6C7C76",
"accent": "#087F70",
"accent_hover": "#0A9684",
"accent_dark": "#D6F0EB",
"error": "#B42318",
"checker_a": "#EBEFED",
"checker_b": "#DDE4E1",
}
COLORS = dict(DARK_COLORS)
def resource_path(relative: str) -> Path:
base = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
return base / relative
def enable_high_dpi() -> None:
if sys.platform != "win32":
return
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
try:
ctypes.windll.user32.SetProcessDPIAware()
except Exception:
pass
try:
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
"PerfectPixel.Studio.2"
)
except Exception:
pass
def windows_theme() -> str:
"""Return the Windows application theme as ``light`` or ``dark``."""
if sys.platform != "win32" or winreg is None:
return "dark"
try:
path = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as key:
value, _ = winreg.QueryValueEx(key, "AppsUseLightTheme")
return "light" if int(value) else "dark"
except OSError:
return "dark"
class HoverButton(tk.Label):
"""A compact flat button with predictable hover/disabled states."""
def __init__(
self,
master,
text: str,
command=None,
*,
primary: bool = False,
small: bool = False,
width: int | None = None,
anchor: str = "center",
):
self.command = command
self.primary = primary
self.enabled = True
self.selected = False
self.normal_bg = COLORS["accent"] if primary else COLORS["surface"]
self.hover_bg = COLORS["accent_hover"] if primary else COLORS["surface_hover"]
self.active_bg = COLORS["accent_dark"] if not primary else COLORS["accent_hover"]
self.normal_fg = COLORS["bg"] if primary else COLORS["text_soft"]
kwargs = {
"text": text,
"bg": self.normal_bg,
"fg": self.normal_fg,
"activebackground": self.hover_bg,
"activeforeground": self.normal_fg,
"font": (UI_FONT, 9 if small else 10, "bold"),
"cursor": "hand2",
"padx": 12 if small else 18,
"pady": 7 if small else 11,
"anchor": anchor,
"takefocus": True,
"highlightthickness": 1,
"highlightbackground": COLORS["line"],
"highlightcolor": COLORS["accent"],
}
if width is not None:
kwargs["width"] = width
super().__init__(master, **kwargs)
self.bind("<Enter>", self._enter)
self.bind("<Leave>", self._leave)
self.bind("<Button-1>", self._click)
self.bind("<Return>", self._click)
self.bind("<space>", self._click)
def _enter(self, _event=None):
if self.enabled:
self.configure(bg=self.hover_bg)
def _leave(self, _event=None):
if self.enabled:
self.configure(bg=self.active_bg if self.selected else self.normal_bg)
def _click(self, _event=None):
if self.enabled and self.command:
self.command()
def set_enabled(self, enabled: bool):
self.enabled = enabled
self.configure(
cursor="hand2" if enabled else "arrow",
bg=(self.active_bg if self.selected else self.normal_bg)
if enabled
else COLORS["surface"],
fg=self.normal_fg if enabled else COLORS["muted"],
)
def set_selected(self, selected: bool):
self.selected = selected
if self.enabled:
self.configure(
bg=self.active_bg if selected else self.normal_bg,
fg=COLORS["accent"] if selected and not self.primary else self.normal_fg,
highlightbackground=COLORS["accent"] if selected else COLORS["line"],
)
class ScrollFrame(tk.Frame):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.canvas = tk.Canvas(
self,
bg=self["bg"],
highlightthickness=0,
borderwidth=0,
)
self.scrollbar = ttk.Scrollbar(
self, orient="vertical", command=self.canvas.yview
)
self.content = tk.Frame(self.canvas, bg=self["bg"])
self.window_id = self.canvas.create_window(
(0, 0), window=self.content, anchor="nw"
)
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.pack(side="left", fill="both", expand=True)
self.scrollbar.pack(side="right", fill="y")
self.content.bind("<Configure>", self._content_resized)
self.canvas.bind("<Configure>", self._canvas_resized)
self.canvas.bind("<Enter>", lambda _e: self._bind_wheel(True))
self.canvas.bind("<Leave>", lambda _e: self._bind_wheel(False))
def _content_resized(self, _event=None):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def _canvas_resized(self, event):
self.canvas.itemconfigure(self.window_id, width=event.width)
def _bind_wheel(self, bind: bool):
if bind:
self.canvas.bind_all("<MouseWheel>", self._wheel)
else:
self.canvas.unbind_all("<MouseWheel>")
def _wheel(self, event):
self.canvas.yview_scroll(int(-event.delta / 120), "units")
class LabeledScale(tk.Frame):
def __init__(
self,
master,
label: str,
variable,
minimum: float,
maximum: float,
*,
resolution: float = 1,
suffix: str = "",
formatter=None,
):
super().__init__(master, bg=master["bg"])
self.variable = variable
self.suffix = suffix
self.formatter = formatter
top = tk.Frame(self, bg=self["bg"])
top.pack(fill="x")
tk.Label(
top,
text=label,
bg=self["bg"],
fg=COLORS["text_soft"],
font=(UI_FONT, 9),
).pack(side="left")
self.value_label = tk.Label(
top,
bg=self["bg"],
fg=COLORS["accent"],
font=(UI_FONT, 9, "bold"),
)
self.value_label.pack(side="right")
self.scale = tk.Scale(
self,
from_=minimum,
to=maximum,
resolution=resolution,
orient="horizontal",
variable=variable,
showvalue=False,
bg=self["bg"],
fg=COLORS["text"],
troughcolor=COLORS["line"],
activebackground=COLORS["accent_hover"],
highlightthickness=0,
borderwidth=0,
sliderlength=16,
sliderrelief="flat",
length=260,
command=lambda _value: self._update_value(),
)
self.scale.pack(fill="x", pady=(2, 0))
self._update_value()
def _update_value(self):
value = self.variable.get()
text = self.formatter(value) if self.formatter else f"{value:g}"
self.value_label.configure(text=f"{text}{self.suffix}")
class CollapsibleSection(tk.Frame):
def __init__(self, master, title: str, *, open_by_default: bool = False):
super().__init__(master, bg=master["bg"])
self.open = open_by_default
self.header = tk.Frame(self, bg=self["bg"], cursor="hand2")
self.header.pack(fill="x", pady=(6, 0))
self.chevron = tk.Label(
self.header,
text="−" if self.open else "+",
bg=self["bg"],
fg=COLORS["accent"],
font=(UI_FONT, 12, "bold"),
width=2,
)
self.chevron.pack(side="right")
self.title = tk.Label(
self.header,
text=title,
bg=self["bg"],
fg=COLORS["text"],
font=(UI_FONT, 10, "bold"),
)
self.title.pack(side="left")
self.body = tk.Frame(self, bg=self["bg"])
if self.open:
self.body.pack(fill="x", pady=(10, 4))
for widget in (self.header, self.title, self.chevron):
widget.bind("<Button-1>", self.toggle)
tk.Frame(self, bg=COLORS["line_soft"], height=1).pack(
fill="x", pady=(10, 0)
)
def toggle(self, _event=None):
self.open = not self.open
self.chevron.configure(text="−" if self.open else "+")
if self.open:
self.body.pack(fill="x", pady=(10, 4), before=self.winfo_children()[-1])
else:
self.body.pack_forget()
class PerfectPixelApp:
PRESETS = {
"智能优化": {
"sample_method": "中心取样",
"max_colors": 0,
"posterize_enabled": False,
"morph_cleanup": False,
"background_enabled": False,
"alpha_binarize": False,
},
"保留原色": {
"sample_method": "中位数",
"max_colors": 0,
"posterize_enabled": False,
"morph_cleanup": False,
"background_enabled": False,
"alpha_binarize": False,
},
"复古限色": {
"sample_method": "多数色",
"max_colors": 16,
"posterize_enabled": True,
"posterize_bits": 5,
"morph_cleanup": True,
"background_enabled": False,
"alpha_binarize": False,
},
"透明背景": {
"sample_method": "中心取样",
"max_colors": 0,
"posterize_enabled": False,
"morph_cleanup": False,
"background_enabled": True,
"background_transparent": True,
"alpha_binarize": True,
},
}
def __init__(self, root: tk.Tk):
self.root = root
self.theme_mode = "跟随系统"
self.effective_theme = windows_theme()
COLORS.clear()
COLORS.update(
LIGHT_COLORS if self.effective_theme == "light" else DARK_COLORS
)
self.source_array: np.ndarray | None = None
self.source_path: Path | None = None
self.source_name = "pixel_art.png"
self.result: ProcessResult | None = None
self.current_view = "source"
self.last_export_folder: Path | None = None
self.preview_photo = None
self.preview_resize_job = None
self.busy = False
self.current_preset = "智能优化"
self.status_text = "准备就绪"
self.status_kind = "normal"
self.events: queue.Queue = queue.Queue()
self.vars: dict[str, tk.Variable] = {}
self.view_buttons: dict[str, HoverButton] = {}
self.export_buttons: list[HoverButton] = []
self._setup_window()
self._setup_styles()
self._create_variables()
self._build_layout()
self._bind_shortcuts()
self.root.after(60, self._poll_events)
self.root.after(80, self._fade_in)
self.root.after(120, self._apply_titlebar_theme)
self.root.after(2000, self._check_system_theme)
def _setup_window(self):
self.root.title(f"{APP_NAME} — 像素画精修工作台")
self.root.configure(bg=COLORS["bg"])
self.root.minsize(1100, 700)
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
width = min(1320, max(1100, screen_width - 80))
height = min(840, max(700, screen_height - 100))
x = max(0, (screen_width - width) // 2)
y = max(0, (screen_height - height) // 2)
self.root.geometry(f"{width}x{height}+{x}+{y}")
self.root.option_add("*tearOff", False)
self.root.attributes("-alpha", 0.0)
icon = resource_path("assets/perfect_pixel.ico")
if icon.exists():
try:
self.root.iconbitmap(default=str(icon))
except tk.TclError:
pass
def _setup_styles(self):
style = ttk.Style(self.root)
try:
style.theme_use("clam")
except tk.TclError:
pass
style.configure(
"TScrollbar",
background=COLORS["line"],
troughcolor=COLORS["sidebar"],
bordercolor=COLORS["sidebar"],
arrowcolor=COLORS["muted"],
width=9,
)
style.configure(
"TCombobox",
fieldbackground=COLORS["surface"],
background=COLORS["surface"],
foreground=COLORS["text"],
arrowcolor=COLORS["accent"],
bordercolor=COLORS["line"],
lightcolor=COLORS["line"],
darkcolor=COLORS["line"],
padding=8,
)
style.map(
"TCombobox",
fieldbackground=[("readonly", COLORS["surface"])],
foreground=[("readonly", COLORS["text"])],
selectbackground=[("readonly", COLORS["surface"])],
selectforeground=[("readonly", COLORS["text"])],
)
style.configure(
"Accent.Horizontal.TProgressbar",
troughcolor=COLORS["line_soft"],
background=COLORS["accent"],
bordercolor=COLORS["line_soft"],
lightcolor=COLORS["accent"],
darkcolor=COLORS["accent"],
thickness=3,
)
def _create_variables(self):
defaults = {
"sample_method": (tk.StringVar, "中心取样"),
"processing_order": (tk.StringVar, "先对齐,再量化"),
"scale_factor": (tk.IntVar, 8),
"max_colors": (tk.IntVar, 0),
"color_space": (tk.StringVar, "OKLab"),
"posterize_enabled": (tk.BooleanVar, False),
"posterize_bits": (tk.IntVar, 5),
"grid_width": (tk.StringVar, "0"),
"grid_height": (tk.StringVar, "0"),
"min_pixel_size": (tk.DoubleVar, 4.0),
"peak_width": (tk.IntVar, 6),
"refine_intensity": (tk.DoubleVar, 0.25),
"fix_square": (tk.BooleanVar, True),
"dominant_enabled": (tk.BooleanVar, False),
"dominant_threshold": (tk.DoubleVar, 0.5),
"morph_cleanup": (tk.BooleanVar, False),
"antialias_cleanup": (tk.BooleanVar, False),
"antialias_threshold": (tk.IntVar, 30),
"background_enabled": (tk.BooleanVar, False),
"background_color": (tk.StringVar, "#ffffff"),
"background_tolerance": (tk.IntVar, 30),
"background_transparent": (tk.BooleanVar, True),
"alpha_binarize": (tk.BooleanVar, False),
"alpha_threshold": (tk.IntVar, 128),
}
self.vars = {name: kind(value=value) for name, (kind, value) in defaults.items()}
def _build_layout(self):
self._build_header()
body = tk.Frame(self.root, bg=COLORS["bg"])
body.pack(fill="both", expand=True)
self.sidebar = ScrollFrame(body, bg=COLORS["sidebar"], width=350)
self.sidebar.pack(side="left", fill="y")
self.sidebar.pack_propagate(False)
tk.Frame(body, bg=COLORS["line_soft"], width=1).pack(side="left", fill="y")
self.main = tk.Frame(body, bg=COLORS["bg"])
self.main.pack(side="left", fill="both", expand=True)
self._build_sidebar()
self._build_workspace()
self._register_file_drop()
def _build_header(self):
header = tk.Frame(self.root, bg=COLORS["bg"], height=72)
header.pack(fill="x")
header.pack_propagate(False)
brand = tk.Frame(header, bg=COLORS["bg"])
brand.pack(side="left", padx=(24, 0), pady=13)
mark = tk.Canvas(
brand, width=38, height=38, bg=COLORS["bg"], highlightthickness=0
)
mark.pack(side="left", padx=(0, 12))
mark.create_rectangle(2, 2, 17, 17, fill=COLORS["accent"], outline="")
mark.create_rectangle(21, 2, 36, 17, fill=COLORS["line"], outline="")
mark.create_rectangle(2, 21, 17, 36, fill=COLORS["line"], outline="")
mark.create_rectangle(21, 21, 36, 36, fill=COLORS["accent"], outline="")
names = tk.Frame(brand, bg=COLORS["bg"])
names.pack(side="left")
tk.Label(
names,
text="PERFECT PIXEL",
bg=COLORS["bg"],
fg=COLORS["text"],
font=(UI_FONT, 14, "bold"),
).pack(anchor="w")
self.header_status = tk.Label(
header,
text=self.status_text,
bg=COLORS["accent_dark"],
fg=COLORS["accent"],
font=(UI_FONT, 9, "bold"),
padx=12,
pady=6,
)
self.header_status.pack(side="right", padx=24)
self.theme_button = tk.Menubutton(
header,
text=f"主题 {self.theme_mode} ▾",
bg=COLORS["surface"],
fg=COLORS["text_soft"],
activebackground=COLORS["surface_hover"],
activeforeground=COLORS["text"],
relief="flat",
borderwidth=0,
highlightthickness=1,
highlightbackground=COLORS["line"],
cursor="hand2",
font=(UI_FONT, 9, "bold"),
padx=12,
pady=6,
)
theme_menu = tk.Menu(
self.theme_button,
tearoff=False,
bg=COLORS["surface"],
fg=COLORS["text"],
activebackground=COLORS["accent_dark"],
activeforeground=COLORS["text"],
borderwidth=1,
relief="flat",
font=(UI_FONT, 9),
)
for mode in ("跟随系统", "浅色", "深色"):
theme_menu.add_command(
label=("✓ " if self.theme_mode == mode else " ") + mode,
command=lambda selected=mode: self.set_theme_mode(selected),
)
self.theme_button.configure(menu=theme_menu)
self.theme_button.pack(side="right")
tk.Frame(self.root, bg=COLORS["line_soft"], height=1).pack(fill="x")
def _build_sidebar(self):
content = self.sidebar.content
inner = tk.Frame(content, bg=COLORS["sidebar"])
inner.pack(fill="both", expand=True, padx=20, pady=20)
self.drop_frame = tk.Frame(
inner,
bg=COLORS["surface"],
highlightthickness=1,
highlightbackground=COLORS["line"],
cursor="hand2",
)
self.drop_frame.pack(fill="x")
self.drop_frame.bind("<Button-1>", lambda _e: self.open_image())
drop_content = tk.Frame(self.drop_frame, bg=COLORS["surface"])
drop_content.pack(fill="x", padx=16, pady=16)
drop_content.bind("<Button-1>", lambda _e: self.open_image())
tk.Label(
drop_content,
text="导入图片",
bg=COLORS["surface"],
fg=COLORS["text"],
font=(UI_FONT, 11, "bold"),
).pack(anchor="w")
self.source_label = tk.Label(
drop_content,
text="拖入图片到窗口任意位置\n也可以点击选择或按 Ctrl + V",
bg=COLORS["surface"],
fg=COLORS["muted"],
justify="left",
font=(UI_FONT, 9),
pady=7,
wraplength=260,
)
self.source_label.pack(anchor="w")
self.source_label.bind("<Button-1>", lambda _e: self.open_image())
actions = tk.Frame(drop_content, bg=COLORS["surface"])
actions.pack(fill="x", pady=(4, 0))
HoverButton(actions, "选择图片", self.open_image, small=True).pack(side="left")
HoverButton(actions, "粘贴", self.paste_image, small=True).pack(
side="left", padx=(8, 0)
)
self._section_heading(inner, "快速预设", top=20)
presets = tk.Frame(inner, bg=COLORS["sidebar"])
presets.pack(fill="x")
self.preset_buttons = {}
for index, name in enumerate(self.PRESETS):
button = HoverButton(
presets,
name,
command=lambda selected=name: self.apply_preset(selected),
small=True,
)
button.grid(
row=index // 2,
column=index % 2,
sticky="ew",
padx=(0, 5) if index % 2 == 0 else (5, 0),
pady=(0, 8),
)
presets.grid_columnconfigure(index % 2, weight=1)
self.preset_buttons[name] = button
if self.current_preset in self.preset_buttons:
self.preset_buttons[self.current_preset].set_selected(True)
self._section_heading(inner, "核心设置", top=12)
self._dropdown(
inner,
"采样方式",
self.vars["sample_method"],
("中心取样", "中位数", "多数色"),
)
self._dropdown(
inner,
"处理顺序",
self.vars["processing_order"],
("先对齐,再量化", "先量化,再对齐"),
)
LabeledScale(
inner,
"输出放大倍数",
self.vars["scale_factor"],
1,
32,
suffix="x",
).pack(fill="x", pady=(10, 0))
self.process_button = HoverButton(
inner, "开始精修", self.start_processing, primary=True
)
self.process_button.pack(fill="x", pady=(18, 8))
tk.Label(
inner,
text="快捷键 Ctrl + Enter",
bg=COLORS["sidebar"],
fg=COLORS["muted"],
font=(UI_FONT, 8),
).pack()
color_section = CollapsibleSection(inner, "颜色处理", open_by_default=True)
color_section.pack(fill="x", pady=(12, 0))
LabeledScale(
color_section.body,
"保留颜色数量",
self.vars["max_colors"],
0,
256,
formatter=lambda value: "不限" if int(value) == 0 else str(int(value)),
).pack(fill="x")
self._dropdown(
color_section.body,
"量化色彩空间",
self.vars["color_space"],
("OKLab", "RGB"),
)
self._check(
color_section.body, "启用色阶降低", self.vars["posterize_enabled"]
)
LabeledScale(
color_section.body,
"每通道位数",
self.vars["posterize_bits"],
1,
7,
suffix=" bit",
).pack(fill="x", pady=(8, 0))
grid_section = CollapsibleSection(inner, "网格检测")
grid_section.pack(fill="x")
self._grid_entries(grid_section.body)
LabeledScale(
grid_section.body,
"最小像素尺寸",
self.vars["min_pixel_size"],
1,
20,
resolution=0.5,
suffix=" px",
).pack(fill="x", pady=(8, 0))
LabeledScale(
grid_section.body,
"检测峰宽",
self.vars["peak_width"],
1,
20,
).pack(fill="x", pady=(8, 0))
LabeledScale(
grid_section.body,
"网格修正强度",
self.vars["refine_intensity"],
0,
1,
resolution=0.05,
formatter=lambda value: f"{float(value):.2f}",
).pack(fill="x", pady=(8, 0))
self._check(
grid_section.body,
"自动检测时修正近似正方形",
self.vars["fix_square"],
)
self._check(grid_section.body, "使用主导色阈值采样", self.vars["dominant_enabled"])
LabeledScale(
grid_section.body,
"主导色阈值",
self.vars["dominant_threshold"],
0.1,
1,
resolution=0.05,
formatter=lambda value: f"{float(value):.2f}",
).pack(fill="x", pady=(8, 0))
cleanup_section = CollapsibleSection(inner, "边缘清理")
cleanup_section.pack(fill="x")
self._check(cleanup_section.body, "清理孤立杂色像素", self.vars["morph_cleanup"])
self._check(cleanup_section.body, "清理抗锯齿残留", self.vars["antialias_cleanup"])
LabeledScale(
cleanup_section.body,
"抗锯齿阈值",
self.vars["antialias_threshold"],
5,
100,
).pack(fill="x", pady=(8, 0))
background_section = CollapsibleSection(inner, "透明背景")
background_section.pack(fill="x")
self._check(
background_section.body,
"处理指定背景色",
self.vars["background_enabled"],
)
self._color_input(background_section.body)
LabeledScale(
background_section.body,
"背景色容差",
self.vars["background_tolerance"],
0,
128,
).pack(fill="x", pady=(8, 0))
self._check(
background_section.body,
"替换为透明",
self.vars["background_transparent"],
)
self._check(
background_section.body,
"透明度二值化",
self.vars["alpha_binarize"],
)
LabeledScale(
background_section.body,
"透明度阈值",
self.vars["alpha_threshold"],
0,
255,
).pack(fill="x", pady=(8, 0))
tk.Label(
inner,
text=f"Perfect Pixel Studio v{APP_VERSION}",
bg=COLORS["sidebar"],
fg=COLORS["muted"],
font=(UI_FONT, 8),
).pack(anchor="w", pady=(22, 8))
def _build_workspace(self):
self.view_buttons = {}
self.export_buttons = []
toolbar = tk.Frame(self.main, bg=COLORS["bg"], height=64)
toolbar.pack(fill="x", padx=24)
toolbar.pack_propagate(False)
tabs = tk.Frame(toolbar, bg=COLORS["bg"])
tabs.pack(side="left", pady=12)
for key, text in (
("source", "原图"),
("scaled", "放大预览"),
("original", "原始像素"),
):
button = HoverButton(
tabs,
text,
command=lambda view=key: self.set_view(view),
small=True,
width=9,
)
button.pack(side="left", padx=(0, 8))
self.view_buttons[key] = button
self.view_buttons["source"].set_selected(True)
self.file_meta = tk.Label(
toolbar,
text="尚未导入图片",
bg=COLORS["bg"],
fg=COLORS["muted"],
font=(UI_FONT, 9),
)
self.file_meta.pack(side="right")
self.preview_canvas = tk.Canvas(
self.main,
bg=COLORS["preview"],
highlightthickness=1,
highlightbackground=COLORS["line_soft"],
)
self.preview_canvas.pack(fill="both", expand=True, padx=24)
self.preview_canvas.bind("<Configure>", self._schedule_preview)
self.preview_canvas.bind("<Double-Button-1>", lambda _e: self.open_image())
self._draw_empty_preview()
result_panel = tk.Frame(self.main, bg=COLORS["bg"], height=174)
result_panel.pack(fill="x", padx=24, pady=(0, 18))
result_panel.pack_propagate(False)
self.progress = ttk.Progressbar(
result_panel,
mode="determinate",
maximum=100,
style="Accent.Horizontal.TProgressbar",
)
self.progress.pack(fill="x")
info_row = tk.Frame(result_panel, bg=COLORS["bg"])
info_row.pack(fill="x", pady=(14, 12))
self.metric_values = {}
for index, (key, label) in enumerate(
(
("grid", "像素网格"),
("size", "放大尺寸"),
("colors", "实际颜色"),
("format", "输出格式"),
)
):
metric = tk.Frame(info_row, bg=COLORS["bg"])
metric.pack(side="left", fill="x", expand=True)
if index:
tk.Frame(metric, bg=COLORS["line_soft"], width=1).pack(
side="left", fill="y", padx=(0, 18)
)
tk.Label(
metric,
text=label,
bg=COLORS["bg"],
fg=COLORS["muted"],
font=(UI_FONT, 8),
).pack(anchor="w")
value = tk.Label(
metric,
text="—",
bg=COLORS["bg"],
fg=COLORS["text"],
font=(UI_FONT, 11, "bold"),
)
value.pack(anchor="w", pady=(3, 0))
self.metric_values[key] = value
export_row = tk.Frame(result_panel, bg=COLORS["bg"])
export_row.pack(fill="x")
for text, command, primary in (
("保存原尺寸 PNG", lambda: self.save_image("original"), False),
("保存放大 PNG", lambda: self.save_image("scaled"), False),
("导出全部 ZIP", self.save_zip, True),
):
button = HoverButton(export_row, text, command, primary=primary)
button.pack(side="left", padx=(0, 10))
button.set_enabled(False)
self.export_buttons.append(button)
self.open_folder_button = HoverButton(
export_row, "打开导出目录", self.open_export_folder
)
self.open_folder_button.pack(side="right")
self.open_folder_button.set_enabled(False)
def _section_heading(self, master, text: str, *, top: int = 0):
tk.Label(
master,
text=text.upper(),
bg=master["bg"],
fg=COLORS["muted"],
font=(UI_FONT, 8, "bold"),
).pack(anchor="w", pady=(top, 9))
def _dropdown(self, master, label: str, variable, values):
frame = tk.Frame(master, bg=master["bg"])
frame.pack(fill="x", pady=(0, 10))
tk.Label(
frame,
text=label,
bg=master["bg"],
fg=COLORS["text_soft"],
font=(UI_FONT, 9),
).pack(anchor="w", pady=(0, 5))
ttk.Combobox(
frame,
textvariable=variable,
values=values,
state="readonly",
font=(UI_FONT, 9),
).pack(fill="x")
def _check(self, master, text: str, variable):
check = tk.Checkbutton(
master,
text=text,
variable=variable,
bg=master["bg"],
fg=COLORS["text_soft"],
activebackground=master["bg"],
activeforeground=COLORS["text"],
selectcolor=COLORS["surface_active"],
font=(UI_FONT, 9),
cursor="hand2",
anchor="w",
padx=0,
pady=4,
highlightthickness=0,
)
check.pack(fill="x", pady=(2, 0))
return check
def _grid_entries(self, master):
row = tk.Frame(master, bg=master["bg"])
row.pack(fill="x")
for index, (label, key) in enumerate(
(("手动网格宽", "grid_width"), ("手动网格高", "grid_height"))
):
field = tk.Frame(row, bg=master["bg"])
field.pack(
side="left",
fill="x",
expand=True,
padx=(0, 5) if index == 0 else (5, 0),
)
tk.Label(
field,
text=label,
bg=master["bg"],
fg=COLORS["text_soft"],
font=(UI_FONT, 8),
).pack(anchor="w", pady=(0, 5))
tk.Entry(
field,
textvariable=self.vars[key],
bg=COLORS["surface"],
fg=COLORS["text"],
insertbackground=COLORS["accent"],
relief="flat",
highlightthickness=1,
highlightbackground=COLORS["line"],
highlightcolor=COLORS["accent"],
font=(UI_FONT, 9),
).pack(fill="x", ipady=7)