使用tkinter模块做一个txt文本分割工具
需求场景:将一个有1000行内容的txt文件分割成10个小txt文件,每个文件100行。
需求分析:实现这个需求并不复杂,完全可以通过打开文件,判断行数,输出文件之类的逻辑直接实现,但是如果需要制作图形界面,让不懂代码的人也可以通过点击按钮直接使用这个功能,就相对麻烦一点了。我们希望用户只需要通过运行exe文件就可以体验上述的功能,那么在python中,我们可以借助tkinter进行开发。
- 代码
import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox
import timeit
class Application(tk.Tk):
def __init__(self):
super().__init__()
self.showPath = tk.StringVar()
self.showNumOfLines = tk.StringVar()
self.showRunTime = tk.StringVar()
self.showNumOfLines_handled = tk.StringVar()
self.init_ui()
def init_ui(self):
self.title("Shred the TXT Files")
self.geometry("700x120")
# self.iconbitmap("bitbug_favicon.ico")
self.window = tk.Frame()
self.filePathTextbox = tk.Entry(self.window, textvariable=self.showPath, font=('Arial', 14), width=50,bd=2) # 创建一个文本框,内容显示成明文形式 (导入文件 文本框)
self.filePathTextbox.pack(side='left', padx=10, anchor='nw', pady=10)
self.cutNumTextbox = tk.Entry(self.window, show=None, font=('Arial', 14), width=10, bd=2) # 创建一个文本框,内容显示成明文形式 (分割行数 文本框)
self.cutNumTextbox.place(x=80, y=58, anchor='nw')
self.importFileBotton = tk.Button(self.window, text='导入文件', font=('Arial', 12), width=10, height=1, relief='groove',
activebackground='sky blue', command=self.getLocalFile)
self.importFileBotton.pack(padx=8, anchor='ne', pady=7)
self.cutFileButton = tk.Button(self.window, text='开始处理', font=('Arial', 12), width=10, height=1, relief='groove',
activebackground='sky blue', command=self.cutFile)
self.cutFileButton.pack(padx=8, anchor='e', pady=15)
self.l1 = tk.Label(self.window, text='分割行数:', font=('Arial', 12), width=0, height=2)
self.l1.place(x=7, y=50, anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.l2 = tk.Label(self.window, text='本次处理用时:', font=('Arial', 10), width=0, height=2)
self.l2.place(x=7, y=90, anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.l2_1 = tk.Label(self.window,textvariable=self.showRunTime, font=('Arial', 10), width=0, height=2)
self.l2_1.place(x=60, y=90, anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.l3 = tk.Label(self.window, text='总共处理行数:', font=('Arial', 10), width=0, height=2)
self.l3.place(x=230, y=90, anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.l3_1 = tk.Label(self.window,textvariable=self.showNumOfLines_handled, font=('Arial', 10), width=0, height=2)
self.l3_1.place(x=320, y=90, anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.l4 = tk.Label(self.window, text='*版权归zJay-Liao所有', font=('Arial', 10), width=0, height=2)
self.l4.place(x=430, y=90, anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.l5 = tk.Label(self.window, text='文件总行数:', font=('Arial', 10), width=0, height=2)
self.l5.place(x=230, y=60,anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.l5_1 = tk.Label(self.window, textvariable=self.showNumOfLines, font=('Arial', 10), width=0, height=2)
self.l5_1.place(x=310, y=60, anchor='nw') # Label内容content区域放置位置,自动调节尺寸
self.window.pack(fill=tk.BOTH, expand=True, padx=1, pady=1) # 最后将所有东西显示出来
def getLocalFile(self):
filePath = filedialog.askopenfilename(title="选择文件",
filetypes=(('TXT 文件', '*.txt'), ('所有文件', '*.*')))
self.showPath.set(filePath) # 将导入的文件的路径显示在文本框
self.numOfLines()
def cutFile(self):
start = timeit.default_timer() # 处理文件开始时间
filePath = str(self.filePathTextbox.get()) # 获取文件路径框的内容,即文件路径
if "\\" in filePath:
fileName = filePath.split('\\')[-1] # 分割路径得到文件名(直接复制Windows的路径,显示的是 \)
else:
fileName = filePath.split('/')[-1] # 导入文件路径 显示的是 /
postfix = fileName.split('.')[-1] # 获取文件后缀,用于判断是否为txt文件
if postfix.lower() == "txt": # TXT的大小写不会改变文件性质
try:
numOfCut = int(self.cutNumTextbox.get()) # 获取分割行数的值
count = self.numOfLines()
self.showNumOfLines_handled.set(count) # 将文件行数显示出来
if numOfCut <= 0:
tk.messagebox.showwarning('Warning', '分割行数不能是0或负数!')
elif numOfCut > count:
tk.messagebox.showwarning('Warning', '分割行数大于文件总行数,不需要分割...')
else:
flag = 0
checkCount = 1
with open(filePath) as file_object:
for line in file_object:
if flag == numOfCut:
flag = 0
checkCount += 1
newFileName = filePath[:-4] + "-" + str(checkCount) + ".txt"
with open(newFileName, 'a') as append:
append.write(line.rstrip() + "\n")
flag += 1
except ValueError:
tk.messagebox.showwarning('Warning', '请在 分割行数 中输入整数!')
except FileNotFoundError:
tk.messagebox.showerror('Error', '文件不存在!请检查您的文件路径!')
elif postfix.lower() == "":
tk.messagebox.showwarning('Warning', '请导入文件再进行分割处理!')
else:
tk.messagebox.showwarning('Warning', 'Sorry...目前只支持处理txt文件...')
end = timeit.default_timer() # 处理文件结束时间
runTime = str(end - start)[:8] + "s"
self.showRunTime.set(runTime) # 将处理时间显示出来
def numOfLines(self):
filePath = str(self.filePathTextbox.get()) # 获取文件路径框的内容,即文件路径
count = 0
for index, line in enumerate(open(filePath, 'r')): # 获取文件的行数
count += 1
self.showNumOfLines.set(count) # 将文件行数显示出来
return count
if __name__ == "__main__":
app = Application()
app.mainloop()
- 运行效果
直接运行代码就可以出现以上的操作窗口。将上述的代码打包成exe文件,具体操作在这就不展开了,可以参考之前的文章–pyinstaller打包代码