[Python] 纯文本查看 复制代码 import tkinter as tk
from tkinter import messagebox
import os
import sys
from tkinterdnd2 import DND_FILES, TkinterDnD
class RenameApp:
def __init__(self, root):
self.root = root
self.root.title("批量重命名")
self.root.geometry("240x150")
self.root.resizable(False, False)
# 文件名起始值
tk.Label(root, text="文件名起始值").place(x=23, y=22)
self.start_num = tk.Entry(root)
self.start_num.insert(0, "001")
self.start_num.place(x=117, y=20, width=99, height=22)
# 文件名前缀
tk.Label(root, text="文件名前缀").place(x=24, y=51)
self.prefix = tk.Entry(root)
self.prefix.place(x=117, y=48, width=98, height=21)
# 提示标签
tk.Label(root, text="拖放文件开始重命名", font=('TkDefaultFont', 9, 'bold')).place(x=5, y=120, width=234)
tk.Label(root, text="吾爱破解论坛").place(x=5, y=93, width=234)
# 配置拖放
self.root.drop_target_register(DND_FILES)
self.root.dnd_bind('<<Drop>>', self.on_drop_files)
def on_drop_files(self, event):
files = event.data.split()
# 获取起始值和前缀
start = int(self.start_num.get())
prefix = self.prefix.get()
digits = len(self.start_num.get())
# 处理每个文件
for file_path in files:
file_path = file_path.strip('{}') # 移除可能的花括号
dir_path = os.path.dirname(file_path)
_, ext = os.path.splitext(file_path)
# 生成新文件名
new_name = f"{prefix}{str(start).zfill(digits)}{ext}"
new_path = os.path.join(dir_path, new_name)
try:
os.rename(file_path, new_path)
start += 1
except OSError:
if not messagebox.askyesno("重命名失败",
f"将【{file_path}】重命名为【{new_name}】时失败!\n"
"可能存在重名或文件被占用\n"
"是否跳过并继续?"):
break
# 更新起始值
self.start_num.delete(0, tk.END)
self.start_num.insert(0, str(start).zfill(digits))
def main():
root = TkinterDnD.Tk()
app = RenameApp(root)
root.mainloop()
if __name__ == "__main__":
main() |