使用python结合tkinter实现一个简单的计算当前输入目录下的python文件一共有多少行
import os,time
from threading import Thread
from tkinter import *
root = Tk() # 创建窗口对象
root.title("python代码行数计算")
root.geometry("400x500")
AllFiles = 0
fileCount = 0
fileLines = 0
timer = time.time()
def search(path):
global AllFiles,fileCount,fileLines,timer
fileAndDir = os.listdir(path)
msg = ""
for item in fileAndDir:
if item.startswith("."):
continue
if os.path.isfile(path+"\\"+item):
AllFiles += 1
if item.endswith(".py"):
fileCount += 1
with open(path+"\\"+item,"r",encoding="utf-8") as f:
data = f.read().split("\n")
fileLines += len(data)
text.insert(1.0,f"文件:{item}行数:{ len(data)}\n")
else:
msg = item
else:
if os.path.isdir(path+"\\"+item):
search(path+"\\"+item)
v.set(f"共扫描文件:{AllFiles},py文件数量:{fileCount}, 总代码行数:{fileLines},耗时:{int(time.time()-timer)}s\n当前:{msg}")
def start():
global fileCount,fileLines,AllFiles,timer
AllFiles = 0
fileCount = 0
fileLines = 0
text.delete(1.0,'end')
timer = time.time()
path = E1.get()
# 使用多线程进行计算, 防止计算时主窗体卡死
searTh = Thread(target=search,args=(path,),daemon=True)
searTh.start()
E1 = Entry(root, bd =2)
E1.place(x=5,y=5,width=300)
# 设置输入框的默认值
E1.insert(0,r"C:\")
B = Button(root, text ="开始计算", command = start)
B.place(x=320,y=0)
# 设置滚动条
scroll=Scrollbar()
#设置text的大小以及坐标
text=Text(root,width=50,height=30)
text.place(x=5,y=50)
#将滚动条填充,放在右边,y是竖直方向
scroll.pack(side=RIGHT,fill=Y)
#将滚动条和文本框关联
scroll.config(command=text.yview)
text.config(yscrollcommand=scroll.set)
# 实时的显示当前搜索进度
v = StringVar()
result = Label(root, textvariable=v)
result.place(x=5,y=450)
root.mainloop()
截止文章发布,代码运行无异常.
作者:Eval 2023/4/18