-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
590 lines (518 loc) · 24.1 KB
/
Copy pathgui.py
File metadata and controls
590 lines (518 loc) · 24.1 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
#!/usr/bin/env python3
"""
公文转换器 — Markdown → Word
深色主题 · 点击打开文件 · 无限历史
"""
import json
import re
import os
import subprocess
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path
from datetime import datetime
from docx import Document
from docx.shared import Pt, Mm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml
APP_DIR = Path.home() / ".md2docx"
HISTORY_FILE = APP_DIR / "history.json"
APP_DIR.mkdir(exist_ok=True)
# 公文格式
PAGE = {"width": Mm(210), "height": Mm(297),
"top": Mm(37), "bottom": Mm(35),
"left": Mm(27), "right": Mm(27)}
LINE_SPACING = {"rule": WD_LINE_SPACING.EXACTLY, "val": Pt(28)}
BODY_FONT = {"cn": "仿宋_GB2312", "en": "FangSong", "size": Pt(16)}
TITLE_FONT = {"cn": "方正小标宋", "en": "FZXiaoBiaoSong-B05S", "size": Pt(22), "bold": False}
H1_FONT = {"cn": "黑体", "en": "SimHei", "size": Pt(16), "bold": False}
H2_FONT = {"cn": "楷体", "en": "KaiTi", "size": Pt(16), "bold": True}
H3_FONT = {"cn": "仿宋_GB2312", "en": "FangSong", "size": Pt(16), "bold": True}
H4_FONT = {"cn": "仿宋_GB2312", "en": "FangSong", "size": Pt(16), "bold": False}
CODE_FONT = {"cn": "仿宋_GB2312", "en": "Courier New", "size": Pt(14)}
PAGE_NUM_FONT = {"cn": "宋体", "en": "SimSun", "size": Pt(14)}
# 深色主题配色
C_BG = "#1e1e2e" # 主背景
C_BG2 = "#252536" # 面板背景
C_BG3 = "#2d2d44" # 输入框背景
C_FG = "#cdd6f4" # 主文字
C_FG2 = "#a6adc8" # 次要文字
C_FG3 = "#6c7086" # 更淡文字
C_ACCENT = "#89b4fa" # 强调色(蓝)
C_ACCENT2 = "#a6e3a1" # 成功色(绿)
C_BORDER = "#45475a" # 边框
C_HOVER = "#313244" # 悬停
C_RED = "#f38ba8" # 红色
# ─────────────────────────────────────────────────────────────
# Markdown 解析
# ─────────────────────────────────────────────────────────────
def parse_markdown(text):
blocks = []
lines = text.split('\n')
i = 0
while i < len(lines):
line = lines[i]
if line.strip() == '':
i += 1
continue
if line.strip().startswith('```'):
lang = line.strip()[3:].strip()
code_lines = []
i += 1
while i < len(lines) and not lines[i].strip().startswith('```'):
code_lines.append(lines[i])
i += 1
i += 1
blocks.append(('code', '\n'.join(code_lines), lang))
continue
m = re.match(r'^(#{1,4})\s+(.*)', line)
if m:
blocks.append(('heading', m.group(2).strip(), len(m.group(1))))
i += 1
continue
if re.match(r'^[-*_]{3,}\s*$', line.strip()):
blocks.append(('hr', '', 0))
i += 1
continue
if line.strip().startswith('>'):
quote_lines = []
while i < len(lines) and lines[i].strip().startswith('>'):
quote_lines.append(re.sub(r'^>\s?', '', lines[i]))
i += 1
blocks.append(('quote', '\n'.join(quote_lines), 0))
continue
if '|' in line and i + 1 < len(lines) and re.match(r'^[\s|:-]+$', lines[i + 1]):
table_lines = []
while i < len(lines) and '|' in lines[i]:
table_lines.append(lines[i])
i += 1
blocks.append(('table', table_lines, 0))
continue
m = re.match(r'^(\s*)([-*+])\s+(.*)', line)
if m:
list_items = []
while i < len(lines):
m2 = re.match(r'^(\s*)([-*+])\s+(.*)', lines[i])
if m2:
list_items.append((len(m2.group(1)), m2.group(3)))
i += 1
elif lines[i].strip() == '':
i += 1
break
else:
break
blocks.append(('ul', list_items, 0))
continue
m = re.match(r'^(\s*)(\d+[.)]\s+)(.*)', line)
if m:
list_items = []
while i < len(lines):
m2 = re.match(r'^(\s*)(\d+[.)]\s+)(.*)', lines[i])
if m2:
list_items.append((len(m2.group(1)), m2.group(3)))
i += 1
elif lines[i].strip() == '':
i += 1
break
else:
break
blocks.append(('ol', list_items, 0))
continue
blocks.append(('paragraph', line.strip(), 0))
i += 1
return blocks
# ─────────────────────────────────────────────────────────────
# Word 生成
# ─────────────────────────────────────────────────────────────
def set_run_font(run, font_cfg, bold=False):
run.font.size = font_cfg["size"]
run.font.name = font_cfg["en"]
rPr = run._r.get_or_add_rPr()
rFonts = rPr.find(qn('w:rFonts'))
if rFonts is None:
rFonts = parse_xml(f'<w:rFonts {nsdecls("w")}/>')
rPr.insert(0, rFonts)
rFonts.set(qn('w:ascii'), font_cfg["en"])
rFonts.set(qn('w:hAnsi'), font_cfg["en"])
rFonts.set(qn('w:eastAsia'), font_cfg["cn"])
if bold or font_cfg.get("bold"):
run.font.bold = True
def set_spacing(para):
pf = para.paragraph_format
pf.line_spacing_rule = LINE_SPACING["rule"]
pf.line_spacing = LINE_SPACING["val"]
def add_page_number(section):
footer = section.footer
footer.is_linked_to_previous = False
p = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run("— ")
set_run_font(run, PAGE_NUM_FONT)
for tag, text in [("begin", ""), ("instr", " PAGE "), ("end", "")]:
r = p.add_run()
r._r.append(parse_xml(f'<w:fldChar {nsdecls("w")} w:fldCharType="{tag}"/>'))
set_run_font(r, PAGE_NUM_FONT)
if text:
r2 = p.add_run()
r2._r.append(parse_xml(f'<w:instrText {nsdecls("w")} xml:space="preserve">{text}</w:instrText>'))
set_run_font(r2, PAGE_NUM_FONT)
run = p.add_run(" —")
set_run_font(run, PAGE_NUM_FONT)
def add_inline(para, text, font_cfg, bold=False):
pattern = re.compile(r'(`[^`]+`)|(\*\*\*(.+?)\*\*\*)|(\*\*(.+?)\*\*)|(\*(.+?)\*)')
last = 0
for m in pattern.finditer(text):
if m.start() > last:
run = para.add_run(text[last:m.start()])
set_run_font(run, font_cfg, bold=bold)
if m.group(1):
run = para.add_run(m.group(1)[1:-1])
set_run_font(run, CODE_FONT)
rPr = run._r.get_or_add_rPr()
rPr.append(parse_xml(f'<w:shd {nsdecls("w")} w:val="clear" w:color="auto" w:fill="F0F0F0"/>'))
elif m.group(2):
run = para.add_run(m.group(3))
set_run_font(run, font_cfg, bold=True)
elif m.group(4):
run = para.add_run(m.group(5))
set_run_font(run, font_cfg, bold=True)
elif m.group(6):
run = para.add_run(m.group(7))
set_run_font(run, font_cfg)
last = m.end()
if last < len(text):
run = para.add_run(text[last:])
set_run_font(run, font_cfg, bold=bold)
def generate_docx(markdown_text, output_path):
doc = Document()
section = doc.sections[0]
section.page_width = PAGE["width"]
section.page_height = PAGE["height"]
section.top_margin = PAGE["top"]
section.bottom_margin = PAGE["bottom"]
section.left_margin = PAGE["left"]
section.right_margin = PAGE["right"]
style = doc.styles['Normal']
style.font.size = BODY_FONT["size"]
style.font.name = BODY_FONT["en"]
style.element.rPr.rFonts.set(qn('w:eastAsia'), BODY_FONT["cn"])
style.paragraph_format.line_spacing_rule = LINE_SPACING["rule"]
style.paragraph_format.line_spacing = LINE_SPACING["val"]
defaults = doc.styles.element.find(qn('w:docDefaults'))
if defaults is not None:
rpr = defaults.find(qn('w:rPrDefault'))
if rpr is not None:
rf = rpr.find(qn('w:rPr'))
if rf is not None:
rfonts = rf.find(qn('w:rFonts'))
if rfonts is not None:
rfonts.set(qn('w:ascii'), BODY_FONT["en"])
rfonts.set(qn('w:hAnsi'), BODY_FONT["en"])
rfonts.set(qn('w:eastAsia'), BODY_FONT["cn"])
add_page_number(section)
blocks = parse_markdown(markdown_text)
for block_type, content, extra in blocks:
if block_type == 'heading':
level = extra
if level == 1:
font_cfg = TITLE_FONT
align = WD_ALIGN_PARAGRAPH.CENTER
elif level == 2:
font_cfg = H1_FONT
align = WD_ALIGN_PARAGRAPH.LEFT
elif level == 3:
font_cfg = H2_FONT
align = WD_ALIGN_PARAGRAPH.LEFT
else:
font_cfg = H3_FONT
align = WD_ALIGN_PARAGRAPH.LEFT
para = doc.add_paragraph()
para.alignment = align
set_spacing(para)
para.paragraph_format.space_before = Pt(12)
para.paragraph_format.space_after = Pt(6)
add_inline(para, content, font_cfg, bold=font_cfg.get("bold", False))
elif block_type == 'paragraph':
para = doc.add_paragraph()
set_spacing(para)
para.paragraph_format.space_after = Pt(0)
para.paragraph_format.first_line_indent = Pt(32)
add_inline(para, content, BODY_FONT)
elif block_type in ('ul', 'ol'):
ordered = block_type == 'ol'
for idx, (indent, text) in enumerate(content):
para = doc.add_paragraph()
set_spacing(para)
para.paragraph_format.space_after = Pt(0)
para.paragraph_format.left_indent = Pt(32 + indent * 8)
marker = f"{idx + 1}. " if ordered else "• "
run = para.add_run(marker)
set_run_font(run, BODY_FONT)
add_inline(para, text, BODY_FONT)
elif block_type == 'code':
para = doc.add_paragraph()
para.paragraph_format.space_before = Pt(6)
para.paragraph_format.space_after = Pt(6)
para.paragraph_format.left_indent = Pt(32)
pPr = para._p.get_or_add_pPr()
pPr.append(parse_xml(f'<w:shd {nsdecls("w")} w:val="clear" w:color="auto" w:fill="F5F5F5"/>'))
for j, line in enumerate(content.split('\n')):
if j > 0:
r = para.add_run()
r.add_break()
run = para.add_run(line)
set_run_font(run, CODE_FONT)
elif block_type == 'quote':
for line in content.split('\n'):
para = doc.add_paragraph()
set_spacing(para)
para.paragraph_format.left_indent = Pt(48)
para.paragraph_format.space_after = Pt(0)
add_inline(para, line, BODY_FONT)
elif block_type == 'table':
rows = []
for line in content:
if re.match(r'^[\s|:-]+$', line.strip()):
continue
rows.append([c.strip() for c in line.strip('|').split('|')])
if not rows:
continue
ncols = max(len(r) for r in rows)
table = doc.add_table(rows=len(rows), cols=ncols)
table.alignment = WD_TABLE_ALIGNMENT.CENTER
table.style = 'Table Grid'
for i, rd in enumerate(rows):
for j, ct in enumerate(rd):
if j < ncols:
cell = table.cell(i, j)
cell.text = ''
add_inline(cell.paragraphs[0], ct, BODY_FONT, bold=(i == 0))
elif block_type == 'hr':
para = doc.add_paragraph()
para.paragraph_format.space_before = Pt(6)
para.paragraph_format.space_after = Pt(6)
doc.save(output_path)
return len(blocks)
# ─────────────────────────────────────────────────────────────
# 历史记录
# ─────────────────────────────────────────────────────────────
def load_history():
if HISTORY_FILE.exists():
try:
return json.loads(HISTORY_FILE.read_text(encoding="utf-8"))
except:
return []
return []
def save_history(history):
HISTORY_FILE.write_text(json.dumps(history, ensure_ascii=False, indent=2), encoding="utf-8")
def add_history(text, output_path, block_count):
history = load_history()
history.insert(0, {
"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"output": str(output_path),
"blocks": block_count,
"preview": text[:200].replace("\n", " "),
"text": text,
})
save_history(history)
return history
# ─────────────────────────────────────────────────────────────
# GUI
# ─────────────────────────────────────────────────────────────
class App:
def __init__(self):
self.root = tk.Tk()
self.root.title("公文转换器")
self.root.geometry("960x680")
self.root.minsize(700, 500)
self.root.configure(bg=C_BG)
self._setup_style()
self._setup_ui()
self._refresh_history()
def _setup_style(self):
style = ttk.Style()
style.theme_use("clam")
style.configure(".", background=C_BG, foreground=C_FG, borderwidth=0)
style.configure("TFrame", background=C_BG)
style.configure("TLabel", background=C_BG, foreground=C_FG)
style.configure("TButton", background=C_BG3, foreground=C_FG,
padding=(16, 8), font=("Microsoft YaHei", 10))
style.map("TButton",
background=[("active", C_BORDER), ("pressed", C_ACCENT)],
foreground=[("pressed", C_BG)])
style.configure("Accent.TButton", background=C_ACCENT, foreground=C_BG,
padding=(20, 10), font=("Microsoft YaHei", 11, "bold"))
style.map("Accent.TButton",
background=[("active", "#74c7ec"), ("pressed", "#89dceb")],
foreground=[("pressed", C_BG)])
style.configure("TLabelframe", background=C_BG2, foreground=C_FG2,
borderwidth=1, relief="solid")
style.configure("TLabelframe.Label", background=C_BG2, foreground=C_FG2,
font=("Microsoft YaHei", 10))
style.configure("TSeparator", background=C_BORDER)
style.configure("TScrollbar", background=C_BG3, troughcolor=C_BG,
borderwidth=0, arrowsize=12)
style.map("TScrollbar", background=[("active", C_BORDER)])
def _setup_ui(self):
main = ttk.Frame(self.root, padding=16)
main.pack(fill=tk.BOTH, expand=True)
# 顶部标题栏
header = tk.Frame(main, bg=C_BG)
header.pack(fill=tk.X, pady=(0, 12))
title_frame = tk.Frame(header, bg=C_BG)
title_frame.pack(side=tk.LEFT)
tk.Label(title_frame, text="公文转换器", font=("Microsoft YaHei", 16, "bold"),
bg=C_BG, fg=C_ACCENT).pack(side=tk.LEFT)
tk.Label(title_frame, text=" Markdown → Word", font=("Consolas", 11),
bg=C_BG, fg=C_FG3).pack(side=tk.LEFT, padx=(4, 0), pady=(4, 0))
btn_frame = tk.Frame(header, bg=C_BG)
btn_frame.pack(side=tk.RIGHT)
self.btn_clear = tk.Button(btn_frame, text="清空", command=self._clear,
bg=C_BG3, fg=C_FG2, relief="flat", padx=14, pady=6,
font=("Microsoft YaHei", 10), cursor="hand2")
self.btn_clear.pack(side=tk.RIGHT, padx=(6, 0))
self.btn_clear.bind("<Enter>", lambda e: self.btn_clear.configure(bg=C_BORDER))
self.btn_clear.bind("<Leave>", lambda e: self.btn_clear.configure(bg=C_BG3))
self.btn_gen = tk.Button(btn_frame, text=" 生成 Word ", command=self._generate,
bg=C_ACCENT, fg=C_BG, relief="flat", padx=20, pady=8,
font=("Microsoft YaHei", 11, "bold"), cursor="hand2")
self.btn_gen.pack(side=tk.RIGHT)
self.btn_gen.bind("<Enter>", lambda e: self.btn_gen.configure(bg="#74c7ec"))
self.btn_gen.bind("<Leave>", lambda e: self.btn_gen.configure(bg=C_ACCENT))
# 分割面板
paned = tk.PanedWindow(main, orient=tk.HORIZONTAL, bg=C_BG,
sashwidth=4, sashrelief="flat", borderwidth=0)
paned.pack(fill=tk.BOTH, expand=True)
# 左:输入区
left_frame = tk.Frame(paned, bg=C_BG2, highlightbackground=C_BORDER,
highlightthickness=1)
paned.add(left_frame, width=620, minsize=400)
left_header = tk.Frame(left_frame, bg=C_BG2)
left_header.pack(fill=tk.X, padx=12, pady=(10, 0))
tk.Label(left_header, text="Markdown 输入", font=("Microsoft YaHei", 10, "bold"),
bg=C_BG2, fg=C_FG2).pack(side=tk.LEFT)
input_frame = tk.Frame(left_frame, bg=C_BG3, highlightbackground=C_BORDER,
highlightthickness=1)
input_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=(8, 12))
self.text = tk.Text(input_frame, wrap=tk.WORD, font=("Consolas", 11),
bg=C_BG3, fg=C_FG, insertbackground=C_FG,
selectbackground=C_ACCENT, selectforeground=C_BG,
relief="flat", borderwidth=0, padx=12, pady=10,
spacing1=2, spacing3=2)
text_scroll = tk.Scrollbar(input_frame, command=self.text.yview,
bg=C_BG3, troughcolor=C_BG, width=10)
self.text.configure(yscrollcommand=text_scroll.set)
text_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.text.pack(fill=tk.BOTH, expand=True)
# 右:历史区
right_frame = tk.Frame(paned, bg=C_BG2, highlightbackground=C_BORDER,
highlightthickness=1)
paned.add(right_frame, width=300, minsize=220)
right_header = tk.Frame(right_frame, bg=C_BG2)
right_header.pack(fill=tk.X, padx=12, pady=(10, 0))
tk.Label(right_header, text="历史记录", font=("Microsoft YaHei", 10, "bold"),
bg=C_BG2, fg=C_FG2).pack(side=tk.LEFT)
hist_frame = tk.Frame(right_frame, bg=C_BG3, highlightbackground=C_BORDER,
highlightthickness=1)
hist_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=(8, 12))
self.hist = tk.Listbox(hist_frame, font=("Microsoft YaHei", 9),
bg=C_BG3, fg=C_FG2, selectbackground=C_ACCENT,
selectforeground=C_BG, relief="flat", borderwidth=0,
highlightthickness=0, activestyle="none")
hscroll = tk.Scrollbar(hist_frame, command=self.hist.yview,
bg=C_BG3, troughcolor=C_BG, width=10)
self.hist.configure(yscrollcommand=hscroll.set)
hscroll.pack(side=tk.RIGHT, fill=tk.Y)
self.hist.pack(fill=tk.BOTH, expand=True)
self.hist.bind("<Double-Button-1>", lambda e: self._open_file())
self.hist.bind("<<ListboxSelect>>", self._on_select)
# 历史操作按钮
hist_btn_frame = tk.Frame(right_frame, bg=C_BG2)
hist_btn_frame.pack(fill=tk.X, padx=12, pady=(0, 10))
self.btn_open = tk.Button(hist_btn_frame, text="打开文件", command=self._open_file,
bg=C_BG3, fg=C_ACCENT, relief="flat", padx=12, pady=4,
font=("Microsoft YaHei", 9), cursor="hand2",
state="disabled")
self.btn_open.pack(side=tk.LEFT)
self.btn_open.bind("<Enter>", lambda e: self.btn_open.configure(bg=C_BORDER) if str(self.btn_open["state"]) == "normal" else None)
self.btn_open.bind("<Leave>", lambda e: self.btn_open.configure(bg=C_BG3))
self.btn_del = tk.Button(hist_btn_frame, text="删除", command=self._del_hist,
bg=C_BG3, fg=C_RED, relief="flat", padx=12, pady=4,
font=("Microsoft YaHei", 9), cursor="hand2",
state="disabled")
self.btn_del.pack(side=tk.LEFT, padx=(6, 0))
self.btn_del.bind("<Enter>", lambda e: self.btn_del.configure(bg=C_BORDER) if str(self.btn_del["state"]) == "normal" else None)
self.btn_del.bind("<Leave>", lambda e: self.btn_del.configure(bg=C_BG3))
# 状态栏
status_frame = tk.Frame(main, bg=C_BG2, highlightbackground=C_BORDER,
highlightthickness=1)
status_frame.pack(fill=tk.X, pady=(10, 0))
self.status = tk.StringVar(value="就绪")
tk.Label(status_frame, textvariable=self.status, font=("Microsoft YaHei", 9),
bg=C_BG2, fg=C_FG3, padx=12, pady=6).pack(side=tk.LEFT)
def _clear(self):
self.text.delete("1.0", tk.END)
self.status.set("已清空")
def _generate(self):
content = self.text.get("1.0", tk.END).strip()
if not content:
messagebox.showwarning("提示", "请先粘贴 Markdown 内容")
return
default = datetime.now().strftime("%Y%m%d_%H%M%S") + ".docx"
path = filedialog.asksaveasfilename(
title="保存 Word 文档", defaultextension=".docx",
filetypes=[("Word 文档", "*.docx")], initialfile=default)
if not path:
return
try:
self.status.set("正在生成...")
self.root.update()
n = generate_docx(content, path)
add_history(content, path, n)
self._refresh_history()
name = Path(path).name
self.status.set(f"已生成: {name} ({n} 个块)")
except Exception as e:
self.status.set(f"错误: {e}")
messagebox.showerror("错误", str(e))
def _refresh_history(self):
self.hist.delete(0, tk.END)
self._hist = load_history()
for e in self._hist:
name = Path(e["output"]).name
time_str = e["time"][-8:] # HH:MM:SS
display = f" {time_str} {name}"
self.hist.insert(tk.END, display)
self.btn_open.configure(state="disabled")
self.btn_del.configure(state="disabled")
def _on_select(self, event):
sel = self.hist.curselection()
if sel:
self.btn_open.configure(state="normal")
self.btn_del.configure(state="normal")
def _open_file(self):
sel = self.hist.curselection()
if not sel:
return
e = self._hist[sel[0]]
path = e["output"]
if not Path(path).exists():
messagebox.showwarning("提示", f"文件不存在:\n{path}")
return
os.startfile(path)
def _del_hist(self):
sel = self.hist.curselection()
if not sel:
return
e = self._hist[sel[0]]
name = Path(e["output"]).name
if messagebox.askyesno("确认", f"删除记录?\n{name}"):
self._hist.pop(sel[0])
save_history(self._hist)
self._refresh_history()
def run(self):
self.root.mainloop()
if __name__ == "__main__":
App().run()