import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
from docx import Document
from docx.shared import Cm
from docx.oxml.ns import qn
from docx.enum.section import WD_ORIENT
class DirectoryConverterApp:
def __init__(self, root):
self.root = root
self.root.title("文件转换工具")
self.root.geometry("500x300")
self.root.resizable(True, True)
try:
self.root.option_add("*Font", "SimHei 10")
except:
pass
main_frame = ttk.Frame(root, padding="20")
main_frame.pack(fill=tk.BOTH, expand=True)
dir_frame = ttk.LabelFrame(main_frame, text="选择目录", padding="10")
dir_frame.pack(fill=tk.X, pady=10)
self.dir_path = tk.StringVar()
ttk.Label(dir_frame, text="目录路径:").grid(
row=0, column=0, padx=(5, 0), pady=5, sticky=tk.W
)
dir_entry = ttk.Entry(
dir_frame, textvariable=self.dir_path, width=30
)
dir_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W)
browse_btn = ttk.Button(
dir_frame, text="浏览...", command=self.browse_directory
)
browse_btn.grid(row=0, column=2, padx=(10, 5), pady=5)
btn_frame = ttk.Frame(main_frame, padding=(0, 0, 50, 0))
btn_frame.pack(pady=10)
self.convert_btn = ttk.Button(
btn_frame, text="开始转换", command=self.convert, width=20
)
self.convert_btn.pack(pady=10)
def browse_directory(self):
directory = filedialog.askdirectory(title="选择目录")
if directory:
self.dir_path.set(directory)
def convert(self):
directory = self.dir_path.get()
if not directory:
messagebox.showerror("错误", "请先选择一个目录")
return
input_docx = directory
output_A4_docx = os.path.join(input_docx, 'A4_New_docx')
if not os.path.exists(output_A4_docx):
os.makedirs(output_A4_docx)
all_docx = self.list_docx_files(input_docx)
self.convert_btn.config(state=tk.DISABLED)
for docx in all_docx:
input_docx = docx['file_folder']
output_docx = os.path.join(output_A4_docx, 'A4_' + docx['file_name'] + '.docx')
self.convert_a3_to_a4(input_docx, output_docx)
self.convert_btn.config(state=tk.NORMAL)
messagebox.showinfo("提示", "转换完成")
def convert_a3_to_a4(self,input_docx, output_docx):
doc = Document(input_docx)
for section in doc.sections:
sectPr = section._sectPr
cols = sectPr.xpath('./w:cols')[0] if sectPr.xpath('./w:cols') else None
if cols is not None:
cols.set(qn('w:num'), '1')
if cols.get(qn('w:space')):
cols.set(qn('w:space'), '0')
for section in doc.sections:
section.orientation = WD_ORIENT.PORTRAIT
section.page_height = Cm(29.7)
section.page_width = Cm(21.0)
doc.save(output_docx)
def list_docx_files(self,path):
files = os.listdir(path)
docx_files = []
for file in files:
if file.startswith('~$') or os.path.isdir(os.path.join(path, file)):
continue
if file.endswith('.docx'):
dict_file = {}
dict_file['file_name'] = os.path.splitext(file)[0]
dict_file['file_folder'] = os.path.join(path, file)
docx_files.append(dict_file)
return docx_files
if __name__ == "__main__":
root = tk.Tk()
app = DirectoryConverterApp(root)
root.mainloop()