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
| import tkinter as tk from tkinter import ttk, filedialog, messagebox import subprocess import os from typing import Dict, Any
class FileSettingsDialog(tk.Toplevel): def __init__(self, parent, filename: str, default_ext: str, output_dir: str): super().__init__(parent) self.title(f"文件设置 - {os.path.basename(filename)}") self.filename = filename self.default_ext = default_ext self.output_dir = output_dir base_name = os.path.splitext(os.path.basename(filename))[0] ttk.Label(self, text="自定义输出文件名:").grid(row=0, column=0, padx=5, pady=2, sticky='w') self.custom_name = ttk.Entry(self, width=35) self.custom_name.insert(0, f"{base_name}{self.default_ext}") self.custom_name.grid(row=0, column=1, padx=5, pady=2) ttk.Label(self, text="输出目录:").grid(row=1, column=0, padx=5, pady=2, sticky='w') self.dir_entry = ttk.Entry(self, width=35) self.dir_entry.insert(0, self.output_dir) self.dir_entry.grid(row=1, column=1, padx=5, pady=2) ttk.Button(self, text="浏览...", command=self.browse_dir).grid(row=1, column=2, padx=5) ttk.Button(self, text="保存", command=self.save_settings).grid(row=2, column=1, pady=10)
def browse_dir(self): path = filedialog.askdirectory() if path: self.dir_entry.delete(0, tk.END) self.dir_entry.insert(0, path)
def save_settings(self): self.settings = { 'custom_name': self.custom_name.get(), 'output_dir': self.dir_entry.get() } self.destroy()
class PandocBatchConverter: def __init__(self, root): self.root = root self.root.title("Pandoc 批量转换工具 v2.1") self.root.geometry("800x600") self.global_settings = { 'output_dir': '', 'output_format': '', 'auto_rename': True } self.file_configs: Dict[str, Dict[str, Any]] = {} self.output_formats = self.get_pandoc_formats('--list-output-formats') self.style = ttk.Style() self.style.theme_use('clam') self.create_widgets() if self.output_formats: self.format_combo.current(0) else: messagebox.showerror("错误", "Pandoc未安装或路径配置错误\n" "1. 请访问 https://pandoc.org 下载安装\n" "2. 确保pandoc已添加到系统PATH环境变量") self.root.destroy() def get_pandoc_formats(self, arg): """获取pandoc支持的格式列表""" try: result = subprocess.run(['pandoc', arg], capture_output=True, text=True, check=True) return result.stdout.strip().split('\n') except (subprocess.CalledProcessError, FileNotFoundError): return []
def create_widgets(self): settings_frame = ttk.LabelFrame(self.root, text="全局设置") settings_frame.pack(padx=10, pady=5, fill=tk.X) ttk.Label(settings_frame, text="输出格式:").grid(row=0, column=0, padx=5, sticky='w') self.format_combo = ttk.Combobox(settings_frame, values=self.output_formats, state="readonly") self.format_combo.grid(row=0, column=1, padx=5, sticky='ew') ttk.Label(settings_frame, text="输出目录:").grid(row=1, column=0, padx=5, sticky='w') self.output_dir_entry = ttk.Entry(settings_frame, width=40) self.output_dir_entry.grid(row=1, column=1, padx=5) ttk.Button(settings_frame, text="浏览...", command=self.browse_output_dir).grid(row=1, column=2, padx=5) self.auto_rename_var = tk.BooleanVar(value=True) ttk.Checkbutton(settings_frame, text="自动重命名文件", variable=self.auto_rename_var, command=self.update_all_filenames).grid(row=2, column=1, sticky='w') list_frame = ttk.LabelFrame(self.root, text="文件列表") list_frame.pack(padx=10, pady=5, fill=tk.BOTH, expand=True) self.file_listbox = tk.Listbox(list_frame, selectmode=tk.EXTENDED, width=80, height=15) self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.file_listbox.yview) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.file_listbox.config(yscrollcommand=scrollbar.set) btn_frame = ttk.Frame(self.root) btn_frame.pack(padx=10, pady=5, fill=tk.X) ttk.Button(btn_frame, text="添加文件", command=self.add_files).pack(side=tk.LEFT) ttk.Button(btn_frame, text="移除选中", command=self.remove_selected).pack(side=tk.LEFT) ttk.Button(btn_frame, text="文件设置", command=self.open_file_settings).pack(side=tk.LEFT) ttk.Button(btn_frame, text="开始转换", command=self.start_conversion).pack(side=tk.RIGHT) self.progress = ttk.Progressbar(self.root, orient=tk.HORIZONTAL, mode='determinate') self.progress.pack(padx=10, pady=5, fill=tk.X) self.log_text = tk.Text(self.root, height=8, state=tk.DISABLED) self.log_text.pack(padx=10, pady=5, fill=tk.BOTH, expand=True) self.format_combo.bind("<<ComboboxSelected>>", self.update_all_filenames)
def add_files(self): files = filedialog.askopenfilenames() if files: for file in files: if file not in self.file_configs: self.file_configs[file] = {} self.file_listbox.insert(tk.END, file) self.update_all_filenames()
def remove_selected(self): for i in reversed(self.file_listbox.curselection()): file = self.file_listbox.get(i) del self.file_configs[file] self.file_listbox.delete(i)
def browse_output_dir(self): path = filedialog.askdirectory() if path: self.output_dir_entry.delete(0, tk.END) self.output_dir_entry.insert(0, path) self.global_settings['output_dir'] = path self.update_all_filenames()
def save_global_settings(self): """保存全局设置到配置字典""" self.global_settings['output_dir'] = self.output_dir_entry.get() self.global_settings['output_format'] = self.format_combo.get() messagebox.showinfo("提示", "全局设置已保存")
def update_all_filenames(self, event=None): """更新所有文件的默认输出名称""" base_dir = self.global_settings.get('output_dir', '') output_format = self.global_settings.get('output_format', '') import tkinter as tk from tkinter import ttk, filedialog, messagebox import subprocess import os from typing import Dict, Any
class FileSettingsDialog(tk.Toplevel): def __init__(self, parent, filename: str, default_ext: str, output_dir: str): super().__init__(parent) self.title(f"文件设置 - {os.path.basename(filename)}") self.filename = filename self.default_ext = default_ext self.output_dir = output_dir base_name = os.path.splitext(os.path.basename(filename))[0] ttk.Label(self, text="自定义输出文件名:").grid(row=0, column=0, padx=5, pady=2, sticky='w') self.custom_name = ttk.Entry(self, width=35) self.custom_name.insert(0, f"{base_name}{self.default_ext}") self.custom_name.grid(row=0, column=1, padx=5, pady=2) ttk.Label(self, text="输出目录:").grid(row=1, column=0, padx=5, pady=2, sticky='w') self.dir_entry = ttk.Entry(self, width=35) self.dir_entry.insert(0, self.output_dir) self.dir_entry.grid(row=1, column=1, padx=5, pady=2) ttk.Button(self, text="浏览...", command=self.browse_dir).grid(row=1, column=2, padx=5) ttk.Button(self, text="保存", command=self.save_settings).grid(row=2, column=1, pady=10)
def browse_dir(self): path = filedialog.askdirectory() if path: self.dir_entry.delete(0, tk.END) self.dir_entry.insert(0, path)
def save_settings(self): self.settings = { 'custom_name': self.custom_name.get(), 'output_dir': self.dir_entry.get() } self.destroy()
class PandocBatchConverter: def __init__(self, root): self.root = root self.root.title("Pandoc 批量转换工具 v2.1") self.root.geometry("800x600") self.global_settings = { 'output_dir': '', 'output_format': '', 'auto_rename': True } self.file_configs: Dict[str, Dict[str, Any]] = {} self.output_formats = self.get_pandoc_formats('--list-output-formats') self.style = ttk.Style() self.style.theme_use('clam') self.create_widgets() if self.output_formats: self.format_combo.current(0) else: messagebox.showerror("错误", "Pandoc未安装或路径配置错误\n" "1. 请访问 https://pandoc.org 下载安装\n" "2. 确保pandoc已添加到系统PATH环境变量") self.root.destroy() def get_pandoc_formats(self, arg): """获取pandoc支持的格式列表""" try: result = subprocess.run(['pandoc', arg], capture_output=True, text=True, check=True) return result.stdout.strip().split('\n') except (subprocess.CalledProcessError, FileNotFoundError): return []
def create_widgets(self): settings_frame = ttk.LabelFrame(self.root, text="全局设置") settings_frame.pack(padx=10, pady=5, fill=tk.X) ttk.Label(settings_frame, text="输出格式:").grid(row=0, column=0, padx=5, sticky='w') self.format_combo = ttk.Combobox(settings_frame, values=self.output_formats, state="readonly") self.format_combo.grid(row=0, column=1, padx=5, sticky='ew') ttk.Label(settings_frame, text="输出目录:").grid(row=1, column=0, padx=5, sticky='w') self.output_dir_entry = ttk.Entry(settings_frame, width=40) self.output_dir_entry.grid(row=1, column=1, padx=5) ttk.Button(settings_frame, text="浏览...", command=self.browse_output_dir).grid(row=1, column=2, padx=5) self.auto_rename_var = tk.BooleanVar(value=True) ttk.Checkbutton(settings_frame, text="自动重命名文件", variable=self.auto_rename_var, command=self.update_all_filenames).grid(row=2, column=1, sticky='w') list_frame = ttk.LabelFrame(self.root, text="文件列表") list_frame.pack(padx=10, pady=5, fill=tk.BOTH, expand=True) self.file_listbox = tk.Listbox(list_frame, selectmode=tk.EXTENDED, width=80, height=15) self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.file_listbox.yview) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.file_listbox.config(yscrollcommand=scrollbar.set) btn_frame = ttk.Frame(self.root) btn_frame.pack(padx=10, pady=5, fill=tk.X) ttk.Button(btn_frame, text="添加文件", command=self.add_files).pack(side=tk.LEFT) ttk.Button(btn_frame, text="移除选中", command=self.remove_selected).pack(side=tk.LEFT) ttk.Button(btn_frame, text="文件设置", command=self.open_file_settings).pack(side=tk.LEFT) ttk.Button(btn_frame, text="开始转换", command=self.start_conversion).pack(side=tk.RIGHT) self.progress = ttk.Progressbar(self.root, orient=tk.HORIZONTAL, mode='determinate') self.progress.pack(padx=10, pady=5, fill=tk.X) self.log_text = tk.Text(self.root, height=8, state=tk.DISABLED) self.log_text.pack(padx=10, pady=5, fill=tk.BOTH, expand=True) self.format_combo.bind("<<ComboboxSelected>>", self.update_all_filenames)
def add_files(self): files = filedialog.askopenfilenames() if files: for file in files: if file not in self.file_configs: self.file_configs[file] = {} self.file_listbox.insert(tk.END, file) self.update_all_filenames()
def remove_selected(self): for i in reversed(self.file_listbox.curselection()): file = self.file_listbox.get(i) del self.file_configs[file] self.file_listbox.delete(i)
def browse_output_dir(self): path = filedialog.askdirectory() if path: self.output_dir_entry.delete(0, tk.END) self.output_dir_entry.insert(0, path) self.global_settings['output_dir'] = path self.update_all_filenames()
def update_all_filenames(self, event=None): """更新所有文件的默认输出名称""" base_dir = self.global_settings['output_dir'] output_format = self.format_combo.get() ext = self.get_extension_for_format(output_format)
for file in self.file_configs: if self.auto_rename_var.get(): base_name = os.path.splitext(os.path.basename(file))[0] default_name = f"{base_name}{ext}" self.file_configs[file].setdefault('custom_name', default_name) self.file_configs[file].setdefault('output_dir', base_dir)
def get_extension_for_format(self, fmt: str) -> str: """根据格式获取扩展名""" ext_map = { 'latex': '.tex', 'html': '.html', 'docx': '.docx', 'pdf': '.pdf', 'markdown': '.md', 'epub': '.epub', 'rst': '.rst', 'odt': '.odt', 'rtf': '.rtf' } return ext_map.get(fmt, f'.{fmt}')
def open_file_settings(self): """打开单个文件设置窗口""" selections = self.file_listbox.curselection() if not selections: messagebox.showwarning("提示", "请先选择一个文件") return
file = self.file_listbox.get(selections[0]) config = self.file_configs[file] ext = self.get_extension_for_format(self.format_combo.get()) dlg = FileSettingsDialog( self.root, file, ext, config.get('output_dir', self.global_settings['output_dir']) ) self.root.wait_window(dlg) if hasattr(dlg, 'settings'): self.file_configs[file].update(dlg.settings)
def start_conversion(self): """开始批量转换""" if not self.file_configs: messagebox.showwarning("提示", "请先添加要转换的文件") return
total_files = len(self.file_configs) success_count = 0 failed_files = []
self.progress['maximum'] = total_files self.progress['value'] = 0
for idx, (input_file, config) in enumerate(self.file_configs.items(), 1): try: output_path = os.path.join( config['output_dir'], config['custom_name'] ) subprocess.run( ['pandoc', input_file, '-o', output_path, '-t', self.format_combo.get()], check=True, capture_output=True, text=True ) success_count += 1 self.log(f"{os.path.basename(input_file)} -> 转换成功") except Exception as e: failed_files.append(f"{os.path.basename(input_file)}: {str(e)}") self.log(f"错误: {os.path.basename(input_file)} - {str(e)}", error=True) self.progress['value'] = idx self.root.update()
result_msg = f"转换完成!成功 {success_count}/{total_files} 个文件" if failed_files: result_msg += "\n失败文件:\n" + "\n".join(failed_files) messagebox.showwarning("转换结果", result_msg) else: messagebox.showinfo("转换结果", result_msg)
def log(self, message: str, error=False): """记录日志""" self.log_text.config(state=tk.NORMAL) self.log_text.insert(tk.END, message + '\n') if error: self.log_text.tag_add('error', 'end-1c linestart', 'end-1c lineend') self.log_text.tag_config('error', foreground='red') self.log_text.see(tk.END) self.log_text.config(state=tk.DISABLED)
if __name__ == "__main__": root = tk.Tk() app = PandocBatchConverter(root) root.mainloop()
|