[Python] 纯文本查看 复制代码
import os
import tkinter as tk
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
import threading
def getAllFiles(path):
# 返回指定目录下的所有文件名
return [os.path.join(path, f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
def isUcExtension(file):
# 判断是否是.uc文件
return file.endswith('.uc!')
def ucToFlac(file, output_dir):
# 将指定文件按字节与0xA3进行异或,并对文件格式进行修改
with open(file, 'rb') as fSource:
content = bytearray(fSource.read())
for index in range(len(content)):
content[index] ^= 0xA3
# 确保输出文件名正确处理,只保留一个.mp3后缀
# 先移除".uc!"后缀,然后检查并处理重复的.mp3后缀
output_file_base = file[:-4] # 移除".uc!"后缀
if output_file_base.endswith('.mp3'):
output_file_name = output_file_base # 已经是.mp3结尾,无需改动
else:
output_file_name = output_file_base + '.mp3' # 添加.mp3后缀
output_file = os.path.join(output_dir, os.path.basename(output_file_name))
with open(output_file, 'wb') as fOut:
fOut.write(content)
return output_file
def convertFilesThread(input_dir, output_dir):
if not os.path.isdir(input_dir) or not os.path.isdir(output_dir):
logMessage("错误: 输入或输出目录无效\n")
return
files = getAllFiles(input_dir)
for file in files:
if isUcExtension(file):
output_file = ucToFlac(file, output_dir)
logMessage(os.path.basename(output_file) + ' 转换成功\n')
def convertFiles():
input_dir = input_dir_entry.get()
output_dir = output_dir_entry.get()
# 创建并启动一个新线程来执行耗时的转换任务
threading.Thread(target=convertFilesThread, args=(input_dir, output_dir)).start()
def selectInputDir():
dirname = filedialog.askdirectory()
if dirname:
input_dir_entry.delete(0, tk.END)
input_dir_entry.insert(0, dirname)
def selectOutputDir():
dirname = filedialog.askdirectory()
if dirname:
output_dir_entry.delete(0, tk.END)
output_dir_entry.insert(0, dirname)
def logMessage(message):
# 在文本框中显示信息
if log_text:
log_text.config(state=tk.NORMAL)
log_text.insert(tk.END, message)
log_text.config(state=tk.DISABLED)
log_text.see(tk.END)
# 创建GUI界面
root = tk.Tk()
root.title("UC文件转MP3工具")
# 使用grid布局
tk.Label(root, text="输入目录:").grid(row=0, column=0, sticky='e')
input_dir_entry = tk.Entry(root, width=50)
input_dir_entry.grid(row=0, column=1)
tk.Button(root, text="选择", command=selectInputDir).grid(row=0, column=2)
tk.Label(root, text="输出目录:").grid(row=1, column=0, sticky='e')
output_dir_entry = tk.Entry(root, width=50)
output_dir_entry.grid(row=1, column=1)
tk.Button(root, text="选择", command=selectOutputDir).grid(row=1, column=2)
tk.Button(root, text="开始转换", command=convertFiles).grid(row=2, column=0, columnspan=3)
# 增加一个ScrolledText组件来显示转换日志
log_text = ScrolledText(root, height=10)
log_text.grid(row=3, column=0, columnspan=3, sticky='nsew')
# 配置行列权重,确保GUI元素在窗口调整大小时表现良好
root.grid_rowconfigure(3, weight=1)
root.grid_columnconfigure(1, weight=1)
root.mainloop()