-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslator_gui.py
More file actions
executable file
·2221 lines (1832 loc) · 84.7 KB
/
translator_gui.py
File metadata and controls
executable file
·2221 lines (1832 loc) · 84.7 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
import os
import logging
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, scrolledtext
from pathlib import Path
import threading
import queue
import time
import datetime
from translator import Translator
from config import Config
from service_manager import ServiceManagerWindow
from dictionary_manager import DictionaryManagerWindow
import requests
import csv
from category_manager import CategoryManager
from theme_manager import ThemeManager
import sys
class AudioTranslatorGUI:
# 深色主题配色
COLORS = {
'bg_dark': '#1E1E1E', # 主背景色
'bg_light': '#2D2D2D', # 次要背景
'fg': '#FFFFFF', # 主文本色
'fg_dim': '#AAAAAA', # 次要文本
'accent': '#007ACC', # 强调色
'border': '#3D3D3D', # 边框色
'hover': '#3D3D3D', # 悬停色
'selected': '#094771' # 选中色
}
def __init__(self):
"""初始化 GUI 应用"""
# 创建主窗口
self.window = tk.Tk()
self.window.withdraw() # 先隐藏窗口
# 设置 macOS 窗口样式
if sys.platform == 'darwin':
try:
# 设置窗口按钮命令
self.window.bind('<Command-w>', lambda e: self.on_closing())
self.window.bind('<Command-q>', lambda e: self.on_closing())
self.window.bind('<Command-m>', lambda e: self.window.iconify())
# 设置窗口菜单命令
self.window.createcommand('::tk::mac::Quit', self.on_closing)
self.window.createcommand('::tk::mac::ReopenApplication', lambda: self.window.deiconify())
# 移除窗口样式设置,使用系统默认样式
# 绑定关闭事件
self.window.protocol("WM_DELETE_WINDOW", self.on_closing)
self.window.bind('<Escape>', lambda e: self.on_closing())
except Exception as e:
logging.warning(f"设置 macOS 窗口样式失败: {e}")
def toggle_zoom(self):
"""切换窗口最大化状态"""
state = self.window.wm_state()
if state == 'zoomed':
self.window.wm_state('normal')
else:
self.window.wm_state('zoomed')
# 初始化配置
self.config = Config()
# 设置窗口属性
self.window.title("音效文件名翻译工具")
self.window.geometry("1280x800")
self.window.minsize(800, 600)
# 更新窗口
self.window.update_idletasks()
# 设置主题
ThemeManager.setup_window_theme(self.window, self.config.get("UI_THEME", "dark"))
# 显示窗口
self.window.deiconify()
# 设置可用主题
self.available_themes = ["light", "dark"] # 只保留亮色和暗色主题
saved_theme = self.config.get("UI_THEME", "dark")
if saved_theme not in self.available_themes:
saved_theme = "dark"
# 初始化主题变量
self.theme_var = tk.StringVar(value=saved_theme)
# 初始化分类管理器
self.category_manager = CategoryManager(self.window)
# 添加自动分类选项变量
self.auto_categorize = tk.BooleanVar(value=False)
# 添加子分类选项变量
self.use_subcategory = tk.BooleanVar(value=False)
# 添加批量翻译选项变量
self.batch_translate = tk.BooleanVar(value=True)
self.batch_size = tk.StringVar(value="10")
# 初始化配置和状态
self.translator = Translator(self.config)
self.translation_queue = queue.Queue()
self.is_translating = False
self.pause_event = threading.Event()
self.pause_event.set() # 初始状态为未暂停
# 初始化计数器
self.current_file = 0
self.total_files = 0
# 初始化缓存
self.translation_cache = {}
# 初始化进度变量
self.total_progress_var = tk.DoubleVar(self.window)
self.file_progress_var = tk.DoubleVar(self.window)
# 初始化统计标签字典
self.stats_labels = {}
# 创建主框架
self.main_frame = ttk.Frame(self.window, padding=15)
self.main_frame.grid(row=0, column=0, sticky="nsew")
# 配置主窗口的网格权重
self.window.grid_columnconfigure(0, weight=1)
self.window.grid_rowconfigure(0, weight=1)
# 设置界面
self.setup_ui()
self.load_services()
# 绑定关闭事件
self.window.protocol("WM_DELETE_WINDOW", self.on_closing)
# 创建右键菜单
self.create_context_menu()
def setup_window(self):
"""设置窗口大小和位置"""
screen_width = self.window.winfo_screenwidth()
screen_height = self.window.winfo_screenheight()
width = int(screen_width * 0.8)
height = int(screen_height * 0.8)
# 设置最小窗口大小
self.window.minsize(1200, 800)
# 配置主窗口的网格权重
self.window.grid_columnconfigure(0, weight=1)
self.window.grid_rowconfigure(0, weight=1)
# 设置窗口位置为屏幕中央
x = (screen_width - width) // 2
y = (screen_height - height) // 2
self.window.geometry(f"{width}x{height}+{x}+{y}")
# 允许调整窗口大小
self.window.resizable(True, True)
def setup_theme(self):
"""配置深色主题"""
style = ttk.Style()
# 配置全局样式
style.configure('.',
background=self.COLORS['bg_dark'],
foreground=self.COLORS['fg'],
fieldbackground=self.COLORS['bg_dark'],
borderwidth=1,
relief='flat'
)
# 配置 Treeview 样式
style.configure('Treeview',
background=self.COLORS['bg_dark'],
foreground=self.COLORS['fg'],
fieldbackground=self.COLORS['bg_dark'],
borderwidth=1,
relief='solid'
)
# 配置 Treeview 表头
style.configure('Treeview.Heading',
background=self.COLORS['bg_light'],
foreground=self.COLORS['fg'],
relief='flat',
borderwidth=1
)
# 配置选中和悬停状态
style.map('Treeview',
background=[('selected', self.COLORS['selected'])],
foreground=[('selected', self.COLORS['fg'])]
)
style.map('Treeview.Heading',
background=[('active', self.COLORS['hover'])],
relief=[('pressed', 'sunken')]
)
# 配置按钮样式
style.configure('TButton',
background=self.COLORS['bg_light'],
foreground=self.COLORS['fg'],
borderwidth=1,
relief='solid',
padding=6
)
style.map('TButton',
background=[('active', self.COLORS['hover']),
('pressed', self.COLORS['accent'])],
foreground=[('pressed', self.COLORS['fg'])]
)
# 配置标签样式
style.configure('TLabel',
background=self.COLORS['bg_dark'],
foreground=self.COLORS['fg'],
padding=3
)
# 配置框架样式
style.configure('TFrame',
background=self.COLORS['bg_dark'],
borderwidth=0
)
# 配置分组框样式
style.configure('TLabelframe',
background=self.COLORS['bg_dark'],
foreground=self.COLORS['fg'],
borderwidth=1,
relief='solid'
)
style.configure('TLabelframe.Label',
background=self.COLORS['bg_dark'],
foreground=self.COLORS['fg'],
padding=(6, 3)
)
# 配置进度条样式
style.configure('Horizontal.TProgressbar',
background=self.COLORS['accent'],
troughcolor=self.COLORS['bg_light'],
borderwidth=0,
relief='flat'
)
# 配置下拉框样式
style.configure('TCombobox',
background=self.COLORS['bg_light'],
foreground=self.COLORS['fg'],
fieldbackground=self.COLORS['bg_light'],
selectbackground=self.COLORS['selected'],
selectforeground=self.COLORS['fg'],
arrowcolor=self.COLORS['fg']
)
style.map('TCombobox',
fieldbackground=[('readonly', self.COLORS['bg_light'])],
selectbackground=[('readonly', self.COLORS['selected'])],
selectforeground=[('readonly', self.COLORS['fg'])]
)
# 配置状态栏样式
style.configure('StatusBar.TFrame',
background=self.COLORS['bg_light'],
relief='solid',
borderwidth=1
)
style.configure('StatusBar.TLabel',
background=self.COLORS['bg_light'],
foreground=self.COLORS['fg_dim'],
padding=6
)
# 设置全局选项
self.window.option_add('*TCombobox*Listbox.background', self.COLORS['bg_light'])
self.window.option_add('*TCombobox*Listbox.foreground', self.COLORS['fg'])
self.window.option_add('*TCombobox*Listbox.selectBackground', self.COLORS['selected'])
self.window.option_add('*TCombobox*Listbox.selectForeground', self.COLORS['fg'])
# 设置 macOS 深色模式
try:
self.window.tk.call('tk::unsupported::MacWindowStyle', 'appearance', self.window, 'dark')
self.window.tk.call('tk::unsupported::MacWindowStyle', 'style', self.window, 'plain')
except Exception as e:
logging.warning(f"设置 macOS 深色模式失败: {e}")
# 强制设置窗口背景色
self.window.configure(bg=self.COLORS['bg_dark'])
# 设置全局颜色选项
self.window.option_add('*Background', self.COLORS['bg_dark'])
self.window.option_add('*Foreground', self.COLORS['fg'])
self.window.option_add('*selectBackground', self.COLORS['selected'])
self.window.option_add('*selectForeground', self.COLORS['fg'])
self.window.option_add('*Entry.background', self.COLORS['bg_light'])
self.window.option_add('*Entry.foreground', self.COLORS['fg'])
self.window.option_add('*Text.background', self.COLORS['bg_light'])
self.window.option_add('*Text.foreground', self.COLORS['fg'])
self.window.option_add('*Listbox.background', self.COLORS['bg_light'])
self.window.option_add('*Listbox.foreground', self.COLORS['fg'])
self.window.option_add('*Menu.background', self.COLORS['bg_dark'])
self.window.option_add('*Menu.foreground', self.COLORS['fg'])
self.window.option_add('*Menu.selectColor', self.COLORS['selected'])
self.window.option_add('*Menu.activeBackground', self.COLORS['hover'])
self.window.option_add('*Menu.activeForeground', self.COLORS['fg'])
def setup_ui(self):
"""创建界面组件"""
# 配置主框架的网格权重
self.main_frame.grid_columnconfigure(0, weight=1)
self.main_frame.grid_rowconfigure(2, weight=1) # 文件列表区域可扩展
# 创建菜单栏
self.create_menu()
# 创建工具栏
toolbar = self.create_toolbar(self.main_frame)
toolbar.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)
# 创建文件列表区域
list_frame = ttk.LabelFrame(self.main_frame, text="文件列表", padding=10)
list_frame.grid(row=2, column=0, sticky="nsew", padx=5, pady=(5,0))
list_frame.grid_columnconfigure(0, weight=1)
list_frame.grid_rowconfigure(0, weight=1)
self.create_file_list(list_frame)
# 创建进度信息区域
info_frame = ttk.LabelFrame(self.main_frame, text="翻译进度", padding=10)
info_frame.grid(row=3, column=0, sticky="nsew", padx=5, pady=(5,0))
info_frame.grid_columnconfigure(0, weight=1)
self.create_progress_info(info_frame)
# 创建底部工具栏
bottom_toolbar = self.create_bottom_toolbar(self.main_frame)
bottom_toolbar.grid(row=4, column=0, sticky="nsew", padx=5, pady=5)
# 创建状态栏
self.create_status_bar(self.main_frame)
def create_menu(self):
"""创建菜单栏"""
menubar = tk.Menu(self.window)
self.window.config(menu=menubar)
# 文件菜单
file_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="文件", menu=file_menu)
file_menu.add_command(label="打开文件", command=self.select_files)
file_menu.add_command(label="打开文件夹", command=self.select_folder)
file_menu.add_separator()
file_menu.add_command(label="开始/暂停翻译", command=self.toggle_translation)
file_menu.add_separator()
file_menu.add_command(label="退出", command=self.on_closing)
# 设置菜单
settings_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="设置", menu=settings_menu)
settings_menu.add_command(label="翻译服务配置", command=self.show_service_manager)
settings_menu.add_command(label="词库管理", command=self.show_dictionary_manager)
# 主题菜单
theme_menu = tk.Menu(settings_menu, tearoff=0)
settings_menu.add_cascade(label="界面主题", menu=theme_menu)
# 添加主题选项
for theme in self.available_themes:
theme_menu.add_radiobutton(
label=theme.capitalize(),
variable=self.theme_var,
value=theme,
command=lambda t=theme: self.change_theme(t)
)
def create_toolbar(self, parent):
"""创建工具栏"""
# 创建主工具栏框架
toolbar = ttk.Frame(parent)
# 配置列权重,使工具栏能够自适应宽度
for i in range(3): # 减少为3列,移除翻译控制区
toolbar.grid_columnconfigure(i, weight=1)
# 1. 文件操作区
file_frame = ttk.Labelframe(toolbar, text="文件操作")
file_frame.grid(row=0, column=0, padx=2, sticky="nsew")
file_frame.grid_columnconfigure(0, weight=1)
file_buttons = ttk.Frame(file_frame)
file_buttons.grid(row=0, column=0, sticky="w")
ttk.Button(
file_buttons,
text="添加文件",
command=self.select_files,
width=10
).grid(row=0, column=0, padx=2)
ttk.Button(
file_buttons,
text="添加文件夹",
command=self.select_folder,
width=10
).grid(row=0, column=1, padx=2)
ttk.Button(
file_buttons,
text="清空列表",
command=self.clear_list,
width=10
).grid(row=0, column=2, padx=2)
# 2. 选择工具区
select_frame = ttk.Labelframe(toolbar, text="选择工具")
select_frame.grid(row=0, column=1, padx=2, sticky="nsew")
select_frame.grid_columnconfigure(0, weight=1)
select_buttons = ttk.Frame(select_frame)
select_buttons.grid(row=0, column=0, sticky="w")
ttk.Button(
select_buttons,
text="全选",
command=self.select_all,
width=8
).grid(row=0, column=0, padx=2)
ttk.Button(
select_buttons,
text="取消全选",
command=self.deselect_all,
width=8
).grid(row=0, column=1, padx=2)
ttk.Button(
select_buttons,
text="反选",
command=self.invert_selection,
width=8
).grid(row=0, column=2, padx=2)
# 3. 编辑工具区
edit_frame = ttk.Labelframe(toolbar, text="编辑工具")
edit_frame.grid(row=0, column=2, padx=2, sticky="nsew")
edit_frame.grid_columnconfigure(0, weight=1)
# 批量编辑工具
batch_frame = ttk.Frame(edit_frame)
batch_frame.grid(row=0, column=0, sticky="w")
ttk.Label(batch_frame, text="前缀:").grid(row=0, column=0)
self.prefix_entry = ttk.Entry(batch_frame, width=6)
self.prefix_entry.grid(row=0, column=1, padx=1)
ttk.Label(batch_frame, text="后缀:").grid(row=0, column=2)
self.suffix_entry = ttk.Entry(batch_frame, width=6)
self.suffix_entry.grid(row=0, column=3, padx=1)
ttk.Button(
batch_frame,
text="应用",
command=lambda: self.batch_edit('add'),
width=6
).grid(row=0, column=4, padx=1)
# 替换工具
replace_frame = ttk.Frame(edit_frame)
replace_frame.grid(row=1, column=0, sticky="w", pady=2)
ttk.Label(replace_frame, text="查找:").grid(row=0, column=0)
self.find_entry = ttk.Entry(replace_frame, width=6)
self.find_entry.grid(row=0, column=1, padx=1)
ttk.Label(replace_frame, text="替换:").grid(row=0, column=2)
self.replace_entry = ttk.Entry(replace_frame, width=6)
self.replace_entry.grid(row=0, column=3, padx=1)
ttk.Button(
replace_frame,
text="替换",
command=lambda: self.batch_edit('replace'),
width=6
).grid(row=0, column=4, padx=1)
return toolbar
def create_bottom_toolbar(self, parent):
"""创建底部工具栏"""
bottom_toolbar = ttk.Frame(parent)
# 配置列权重
for i in range(3):
bottom_toolbar.grid_columnconfigure(i, weight=1)
# 1. 翻译操作区
translate_frame = ttk.Labelframe(bottom_toolbar, text="翻译操作")
translate_frame.grid(row=0, column=0, padx=2, sticky="nsew")
translate_frame.grid_columnconfigure(0, weight=1)
# 翻译服务和模型选择
service_frame = ttk.Frame(translate_frame)
service_frame.grid(row=0, column=0, sticky="w")
# 第一行:服务和模型选择
ttk.Label(service_frame, text="服务:").grid(row=0, column=0)
self.service_combo = ttk.Combobox(
service_frame,
width=15,
state="readonly"
)
self.service_combo.grid(row=0, column=1, padx=2)
ttk.Label(service_frame, text="模型:").grid(row=0, column=2)
self.model_combo = ttk.Combobox(
service_frame,
width=15,
state="readonly"
)
self.model_combo.grid(row=0, column=3, padx=2)
# 第二行:翻译选项
options_frame = ttk.Frame(service_frame)
options_frame.grid(row=1, column=0, columnspan=4, sticky="w", pady=(5,0))
# 翻译选项
ttk.Checkbutton(
options_frame,
text="翻译后自动分类",
variable=self.auto_categorize
).grid(row=0, column=0, padx=5)
# 添加批量翻译选项
batch_frame = ttk.Frame(options_frame)
batch_frame.grid(row=0, column=1, padx=5)
ttk.Checkbutton(
batch_frame,
text="批量翻译",
variable=self.batch_translate
).pack(side=tk.LEFT)
ttk.Label(
batch_frame,
text="批次大小:"
).pack(side=tk.LEFT, padx=(5, 0))
# 批次大小选择框
batch_size_combo = ttk.Combobox(
batch_frame,
textvariable=self.batch_size,
values=["5", "10", "20", "50"],
width=5,
state="readonly"
)
batch_size_combo.pack(side=tk.LEFT, padx=2)
# 第三行:操作按钮
btn_frame = ttk.Frame(service_frame)
btn_frame.grid(row=2, column=0, columnspan=4, sticky="w", pady=(5,0))
ttk.Button(
btn_frame,
text="预览翻译",
command=self.preview_translation,
width=10
).grid(row=0, column=0, padx=5)
self.control_btn = ttk.Button(
btn_frame,
text="开始翻译",
command=self.toggle_translation,
width=10,
state='disabled' # 初始状态为禁用
)
self.control_btn.grid(row=0, column=1, padx=5)
# 添加确认重命名按钮
self.rename_btn = ttk.Button(
btn_frame,
text="确认重命名",
command=self.apply_rename,
width=10,
state='disabled' # 初始状态为禁用
)
self.rename_btn.grid(row=0, column=2, padx=5)
# 2. 分类管理区
category_frame = ttk.Labelframe(bottom_toolbar, text="分类管理")
category_frame.grid(row=0, column=1, padx=2, sticky="nsew")
category_frame.grid_columnconfigure(0, weight=1)
category_buttons = ttk.Frame(category_frame)
category_buttons.grid(row=0, column=0, sticky="w")
ttk.Button(
category_buttons,
text="手动分类",
command=self.categorize_selected_files,
width=8
).grid(row=0, column=0, padx=2)
ttk.Button(
category_buttons,
text="自动分类",
command=self.auto_categorize_files,
width=8
).grid(row=0, column=1, padx=2)
# 子分类选项
ttk.Checkbutton(
category_buttons,
text="使用子分类",
variable=self.use_subcategory
).grid(row=0, column=2, padx=2)
# 3. 管理工具区
manage_frame = ttk.Labelframe(bottom_toolbar, text="管理工具")
manage_frame.grid(row=0, column=2, padx=2, sticky="nsew")
manage_frame.grid_columnconfigure(0, weight=1)
manage_buttons = ttk.Frame(manage_frame)
manage_buttons.grid(row=0, column=0, sticky="w")
ttk.Button(
manage_buttons,
text="服务管理",
command=self.show_service_manager,
width=8
).grid(row=0, column=0, padx=2)
ttk.Button(
manage_buttons,
text="词库管理",
command=self.show_dictionary_manager,
width=8
).grid(row=0, column=1, padx=2)
return bottom_toolbar
def load_services(self):
"""加载翻译服务列表"""
try:
# 获取所有服务
services = self.config.get("TRANSLATION_SERVICES", {})
# 更新服务下拉框
service_options = [
f"{service['name']} ({service_id})"
for service_id, service in services.items()
if service.get('enabled', True) # 只显示启用的服务
]
if hasattr(self, 'service_combo'):
self.service_combo['values'] = service_options
# 选中当前使用的服务
current_service = self.config.get("TRANSLATION_SERVICE")
if current_service:
for option in service_options:
if current_service in option:
self.service_combo.set(option)
break
# 加载对应的模型列表
self.load_service_models()
# 绑定服务选择事件
self.service_combo.bind('<<ComboboxSelected>>', self.on_service_change)
except Exception as e:
logging.error(f"加载服务列表失败: {str(e)}")
messagebox.showerror("错误", f"加载服务列表失败: {str(e)}")
def load_service_models(self):
"""加载当前选中服务的模型列表"""
try:
service_text = self.service_combo.get()
if not service_text:
return
# 从选项中提取服务ID
service_id = service_text.split('(')[-1].rstrip(')')
services = self.config.get("TRANSLATION_SERVICES", {})
if service_id in services:
service = services[service_id]
models = service.get("models", [])
# 更新模型下拉框
model_options = [
f"{model['description']} ({model['name']})"
for model in models
]
self.model_combo['values'] = model_options
# 选中当前模型
current_model = service.get("current_model")
if current_model:
for model in models:
if model["name"] == current_model:
self.model_combo.set(f"{model['description']} ({model['name']})")
break
except Exception as e:
logging.error(f"加载模型列表失败: {str(e)}")
def on_service_change(self, event=None):
"""处理服务选择变更"""
try:
# 加载新服务的模型
self.load_service_models()
# 更新配置
service_text = self.service_combo.get()
if service_text:
service_id = service_text.split('(')[-1].rstrip(')')
self.config.set("TRANSLATION_SERVICE", service_id)
self.config.save()
except Exception as e:
logging.error(f"切换服务失败: {str(e)}")
messagebox.showerror("错误", f"切换服务失败: {str(e)}")
def get_current_service_and_model(self):
"""获取当前选中的服务和模型"""
service_text = self.service_combo.get()
model_text = self.model_combo.get()
if not service_text or not model_text:
return None, None
service_id = service_text.split('(')[-1].rstrip(')')
model_name = model_text.split('(')[-1].rstrip(')')
return service_id, model_name
def create_file_list(self, parent):
"""创建文件列表"""
try:
# 创建列表容器
list_container = ttk.Frame(parent)
list_container.pack(fill=tk.BOTH, expand=True)
# 配置列表容器的网格权重
list_container.grid_columnconfigure(0, weight=1)
list_container.grid_rowconfigure(0, weight=1)
# 创建树形列表
columns = ("选择", "原文件名", "翻译后文件名", "状态")
self.tree = ttk.Treeview(
list_container,
columns=columns,
show="headings",
selectmode="extended"
)
# 配置列
column_widths = {
"选择": 60,
"原文件名": 400,
"翻译后文件名": 400,
"状态": 100
}
for col in columns:
self.tree.heading(col, text=col, command=lambda c=col: self.sort_column(c))
self.tree.column(col, width=column_widths[col], minwidth=column_widths[col]//2, stretch=True)
# 添加滚动条
yscroll = ttk.Scrollbar(list_container, orient=tk.VERTICAL, command=self.tree.yview)
xscroll = ttk.Scrollbar(list_container, orient=tk.HORIZONTAL, command=self.tree.xview)
self.tree.configure(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set)
# 使用网格布局
self.tree.grid(row=0, column=0, sticky="nsew")
yscroll.grid(row=0, column=1, sticky="ns")
xscroll.grid(row=1, column=0, sticky="ew")
# 绑定事件
self.tree.bind('<Double-1>', self.edit_filename)
self.tree.bind('<Button-1>', self.on_click)
self.tree.bind('<<TreeviewSelect>>', self.update_file_count)
self.tree.bind('<space>', self.toggle_selection)
self.tree.bind('<Control-a>', self.select_all)
self.tree.bind('<Delete>', self.remove_selected)
self.tree.bind('<Button-3>', self.show_context_menu)
return list_container
except Exception as e:
logging.error(f"创建文件列表时出错: {str(e)}")
raise
def edit_filename(self, event):
"""编辑文件名"""
try:
# 获取选中的项目
if event:
item = self.tree.identify_row(event.y)
else:
selected = self.tree.selection()
if not selected:
return
item = selected[0]
if not item:
return
# 获取当前文件名
current_name = self.tree.set(item, "翻译后文件名")
# 创建编辑对话框
dialog = tk.Toplevel(self.window)
dialog.title("编辑文件名")
dialog.geometry("500x120")
dialog.transient(self.window)
dialog.grab_set()
# 设置深色主题
dialog.configure(bg=self.COLORS['bg_dark'])
try:
dialog.tk.call('tk::unsupported::MacWindowStyle', 'appearance', dialog, 'dark')
dialog.tk.call('tk::unsupported::MacWindowStyle', 'style', dialog, 'plain')
except Exception as e:
logging.warning(f"设置 macOS 深色模式失败: {e}")
# 创建编辑框
frame = ttk.Frame(dialog, padding=10)
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text="新文件名:").pack(pady=(0,5))
entry = ttk.Entry(frame, width=50)
entry.insert(0, current_name)
entry.pack(fill=tk.X, pady=(0,10))
entry.select_range(0, tk.END)
entry.focus_set()
# 按钮区域
btn_frame = ttk.Frame(frame)
btn_frame.pack(fill=tk.X)
def on_ok():
new_name = entry.get()
if new_name and new_name != current_name:
self.tree.set(item, "翻译后文件名", new_name)
self.tree.set(item, "状态", "已修改")
dialog.destroy()
ttk.Button(btn_frame, text="确定", command=on_ok).pack(side=tk.RIGHT, padx=5)
ttk.Button(btn_frame, text="取消", command=dialog.destroy).pack(side=tk.RIGHT)
# 绑定回车键
entry.bind('<Return>', lambda e: on_ok())
# 等待对话框关闭
dialog.wait_window()
except Exception as e:
logging.error(f"编辑文件名时出错: {str(e)}")
def batch_edit(self, mode):
"""批量编辑文件名
Args:
mode: 编辑模式,可选值:
- prefix: 添加前缀
- suffix: 添加后缀
- replace: 替换文本
"""
try:
# 获取选中的项目
selected = [item for item in self.tree.get_children()
if self.tree.set(item, "选择") == "√"]
if not selected:
tk.messagebox.showwarning("警告", "请至少选择一个文件")
return
# 根据模式执行不同的编辑操作
if mode in ("prefix", "suffix"):
text = self.add_text.get().strip()
if not text:
tk.messagebox.showwarning("警告", "请输入要添加的文本")
return
for item in selected:
current_name = self.tree.set(item, "翻译后文件名")
if mode == "prefix":
new_name = text + current_name
else: # suffix
name, ext = os.path.splitext(current_name)
new_name = name + text + ext
self.tree.set(item, "翻译后文件名", new_name)
self.tree.set(item, "状态", "已修改")
elif mode == "replace":
find = self.find_text.get().strip()
replace = self.replace_text.get() # 允许替换为空字符串
if not find:
tk.messagebox.showwarning("警告", "请输入要查找的文本")
return
for item in selected:
current_name = self.tree.set(item, "翻译后文件名")
if find in current_name:
new_name = current_name.replace(find, replace)
self.tree.set(item, "翻译后文件名", new_name)
self.tree.set(item, "状态", "已修改")
except Exception as e:
logging.error(f"批量编辑文件名时出错: {str(e)}")
tk.messagebox.showerror("错误", f"批量编辑文件名时出错: {str(e)}")
def toggle_translation(self, auto_categorize=False):
"""切换翻译状态"""
try:
if not self.is_translating:
# 开始翻译
selected = [item for item in self.tree.get_children()
if self.tree.set(item, "选择") == "√"]
if not selected:
messagebox.showwarning("警告", "请至少选择一个文件")
return
# 设置自动分类选项
if auto_categorize:
self.auto_categorize.set(True)
self.is_translating = True
self.pause_event.set() # 确保未暂停
self.control_btn.configure(text="暂停")
# 启动翻译线程
translation_thread = threading.Thread(
target=self.translation_worker,
args=(selected,),
daemon=True
)
translation_thread.start()
# 启动进度检查
self.window.after(100, self.check_progress)
else:
# 切换暂停/继续状态
if self.pause_event.is_set():
# 暂停翻译
self.pause_event.clear()
self.control_btn.configure(text="继续")
self.status_label.config(text="翻译已暂停")
else:
# 继续翻译
self.pause_event.set()
self.control_btn.configure(text="暂停")
self.status_label.config(text="翻译继续")
except Exception as e:
logging.error(f"切换翻译状态时出错: {str(e)}")
messagebox.showerror("错误", f"切换翻译状态时出错: {str(e)}")
def run(self):
"""启动主窗口主循环"""
self.window.mainloop()
def on_click(self, event):
"""处理点击事件"""
try:
region = self.tree.identify_region(event.x, event.y)
if region == "cell":
column = self.tree.identify_column(event.x)
item = self.tree.identify_row(event.y)
if item and column == '#1': # 点击"选择"列
current_state = self.tree.set(item, "选择")
new_state = "" if current_state == "√" else "√"
self.tree.set(item, "选择", new_state)
self.update_file_count()
return "break"
except Exception as e:
logging.error(f"处理点击事件时出错: {e}")
def select_all(self):
"""全选"""
for item in self.tree.get_children():
self.tree.set(item, "选择", "√")
self.update_file_count()
def deselect_all(self):