[Python] 纯文本查看 复制代码
import os
import shutil
from tkinter import messagebox, filedialog, Frame, StringVar, Label, Entry, Button, Tk, DISABLED, NORMAL
import filetype
import threading
import windnd
def count_w_h_x_y(main_root):
# 获取当前屏幕的宽度和高度
screen_width = main_root.winfo_screenwidth()
screen_height = main_root.winfo_screenheight()
_width = int(screen_width * 2.8 / 10)
_height = int(screen_height * 3 / 10)
_float_x = int((screen_width - _width) / 2)
_float_y = int((screen_height - _height) / 2)
return _width, _height, _float_x, _float_y
class TkApplication(Frame):
def __init__(self, master=None):
super().__init__(master)
self.enter_btn = None
self.open_btn = None
self.tk_th = None
self.root_path = StringVar()
self.new_files = StringVar()
self.file_paths = []
self.open_path = ''
self.master = master
self.create_widget()
self.is_dir = False
self.is_file = False
def create_widget(self):
"""
原文件支持类型:
image:jpg,png,gif,web,cr2,tif,bmp,jxr,psd,ico
video:mp4,m4v,mkv,web,mov,avi,wmv,mpg,flv
audio:mid,mp3,m4a,ogg,flac,wav,amr
application: epub,zip,tar,rar,gz,bz2,7z,xz,pdf,exe,swf,rtf,eot,ps,sqlite,nes,crx,cab,deb,ar,Z,lz
font: woff,woff2,ttf,otf
"""
Label(root, text='选择文件夹: ', font=('华文彩云', 15)).place(x=50, y=80, height=30)
Entry(root, textvariable=self.root_path, font=('FangSong', 10), width=30, state='readonly').place(x=170, y=80,
height=30)
Label(root, text='文件: ', font=('华文彩云', 15)).place(x=50, y=120, height=30)
Entry(root, textvariable=self.new_files, font=('FangSong', 10), width=30, state='readonly').place(x=170, y=120,
height=30)
Button(root, text='选择路径', command=self.get_path).place(x=400, y=80, height=30)
self.enter_btn = Button(root, text='确定(开始执行)', font=('华文彩云', 15),
command=lambda: self.background(self.deal_fix_file))
self.enter_btn['state'] = DISABLED
self.enter_btn.place(x=50, y=160, width=410)
self.open_btn = Button(root, text='打开处理文件夹!', font=('华文彩云', 15), command=self.open)
self.open_btn['state'] = DISABLED
self.open_btn.place(x=50, y=200, width=410)
windnd.hook_dropfiles(self.master, func=self.dragged_files)
def get_path(self):
# 返回一个字符串,可以获取到任意文件的路径。
path1 = filedialog.askdirectory(title='请选择文件')
path1 = path1.replace('/', '\\')
self.root_path.set(path1)
self.file_paths = []
self.open_btn['state'] = DISABLED
self.enter_btn['state'] = NORMAL
self.new_files.set('')
def deal_fix_file(self):
dir_str = self.root_path.get()
if all([not dir_str, not self.file_paths]):
# 请选择路径
messagebox.showwarning('警告!', '请选择路径或文件!')
return
if all([self.is_dir, self.file_paths]):
dir_str = (self.file_paths[0]).replace('/', '\\')
fix_success_dir = os.path.join(dir_str, 'fix_success_dir')
if all([self.is_file, self.file_paths]):
_dir_str, _ = os.path.split(self.file_paths[0])
fix_success_dir = os.path.join(_dir_str, 'fix_success_dir')
if not os.path.exists(fix_success_dir):
os.makedirs(fix_success_dir)
files = self.file_paths
if dir_str:
if not os.listdir(dir_str):
messagebox.showwarning('警告!', '所选文件夹下无文件!')
return
files = os.listdir(dir_str)
for file in files:
if dir_str:
abs_file_path = os.path.join(dir_str, file)
else:
abs_file_path = file
if os.path.isdir(abs_file_path):
continue
try:
kind = filetype.guess(abs_file_path)
if kind is None:
continue
file_type = kind.extension
except Exception as e:
continue
if not dir_str:
_, file = os.path.split(file)
old_file_name, old_file_type = os.path.splitext(file)
if old_file_type.lower() == f'.{file_type}' or not file_type:
continue
new_file = os.path.join(fix_success_dir, f"{old_file_name}.{file_type}")
shutil.copy2(abs_file_path, new_file)
messagebox.showinfo('OK!', '处理完成')
self.open_path = fix_success_dir
self.open_btn['state'] = NORMAL
self.enter_btn['state'] = DISABLED
def open(self):
os.system(f"start {self.open_path}")
self.enter_btn['state'] = DISABLED
def background(self, func):
"""使用线程保证处理文件时不卡顿"""
self.tk_th = threading.Thread(target=func)
self.tk_th.setDaemon(True)
self.tk_th.start()
def dragged_files(self, files):
"""拖拽获取文件路径"""
new_files = []
is_file = False
is_dir = False
for file in files:
try:
file = file.decode('utf-8')
except Exception as e:
file = file.decode('gbk')
finally:
new_files.append(file)
if os.path.isdir(file):
is_dir = True
else:
is_file = True
if all([is_file, is_dir]):
messagebox.showwarning('警告', '禁止文件和文件夹混放!请重新拖拽')
return
if all([is_dir, len(new_files) != 1]):
messagebox.showwarning('警告', '当前版本仅支持拖拽单个文件夹处理!')
return
msg = '\n'.join(new_files)
new_files_msg = ','.join(new_files)
messagebox.showinfo('您拖放的文件', msg)
if is_dir:
self.is_dir = True
else:
self.is_file = True
self.file_paths = new_files
self.new_files.set(new_files_msg)
self.root_path.set('')
self.open_btn['state'] = DISABLED
self.enter_btn['state'] = NORMAL
if __name__ == '__main__':
root = Tk()
root.title('批量修复文件原始格式!')
width, height, float_x, float_y = count_w_h_x_y(root)
root.geometry(f'{width}x{height}+{float_x}+{float_y}') # 设置窗口大小 左上角X,Y坐标
app = TkApplication(master=root)
root.mainloop()