代码统计工具
修改了导出excel功能,把原来的主文件进行了拆分
code_count_windows.py

#encoding=utf-8
import os,sys,time
from collections import defaultdict
from tkinter import *
import tkinter.messagebox
from tkinter import ttk
from tkinter import scrolledtext
import out_save
import code_countroot= Tk()
root.title("有效代码统计工具") #界面的titledef show(): #当按钮被点击,就调用这个方法pathlist=e1.get() #调用get()方法得到在文本框中输入的内容file_types=e2.get().lower()file_types_list=["py","java"]if not pathlist:tkinter.messagebox.showwarning('提示',"请输入文件路径!")return Noneif not file_types:tkinter.messagebox.showwarning('提示',"请输入要统计的类型!")return None#print(type(file_types),file_types)if '\u4e00'<=file_types<='\u9fa5' or not file_types in file_types_list: #判断文件类型输入的是否是中文tkinter.messagebox.showwarning('错误',"输入统计类型有误!")return Nonetext.delete(1.0,END) #删除显示文本框中,原有的内容global code_dictfor path in pathlist.split(";"):path=path.strip()codes,code_dict,space,annotation=code_count.code_count(path,file_types) #将函数返回的结果赋值给变量,方便输出max_code=max(zip(code_dict.values(),code_dict.keys()))#print(codes,code_dict)#print("整个%s有%s类型文件%d个,共有%d行代码"%(path,file_types,len(code_dict),codes))#print("代码最多的是%s,有%d行代码"%(max_code[1],max_code[0]))for k,v in code_dict.items():text.insert(INSERT,"文件%s  有效代码数%s\n"%(k,v[0])) #将文件名和有效代码输出到文本框中text.insert(INSERT,"整个%s下有%s类型文件%d个,共有%d行有效代码\n"%(path,file_types,len(code_dict),codes)) #将结果输出到文本框中text.insert(INSERT,"共有%d行注释\n"%(annotation))text.insert(INSERT,"共有%d行空行\n"%(space))text.insert(INSERT,"代码最多的是%s,有%s行有效代码\n\n"%(max_code[1],max_code[0][0]))frame= Frame(root) #使用Frame增加一层容器
frame.pack(padx=50,pady=40) #设置区域
label= Label(frame,text="路径:",font=("宋体",15),fg="blue").grid(row=0,padx=10,pady=5,sticky=N) #创建标签
labe2= Label(frame,text="类型:",font=("宋体",15),fg="blue").grid(row=1,padx=10,pady=5)
e1= Entry(frame,foreground = 'blue',font = ('Helvetica', '12')) #创建文本输入框
e2= Entry(frame,font = ('Helvetica', '12', 'bold'))
e1.grid(row=0,column=1,sticky=W) #布置文本输入框
e2.grid(row=1,column=1,sticky=W,)
labeltitle=Label(frame,text="输入多个文件路径请使用';'分割",font=("宋体",10,'bold'),fg="red")
labeltitle.grid(row=2,column=1,sticky=NW)
frame.bind_all("<F1>",lambda event:helpinf())
frame.bind_all("<Return>",lambda event:show())
frame.bind_all("<Alt-F4>",lambda event:sys.exit())
frame.bind_all("<Control-s>",lambda event:save())#print(path,file_types)button1= Button(frame ,text=" 提交 ",font=("宋体",13),width=10,command=show).grid(row=3,column=0,padx=15,pady=5) #创建按钮
button2= Button(frame ,text=" 退出 ",font=("宋体",13),width=10,command=root.quit).grid(row=3,column=1,padx=15,pady=5)
#self.hi_there.pack()
text = scrolledtext.ScrolledText(frame,width=40,height=10,font=("宋体",15)) #创建可滚动的文本显示框
text.grid(row=4,column=0,padx=40,pady=15,columnspan=2) #放置文本显示框def save():#print(text.get("0.0","end"))if not text.get("0.0","end").strip(): #获取文本框内容,从开始到结束tkinter.messagebox.showwarning('提示',"还没有统计数据!")return Nonesavecount=''nowtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #获取当前时间并格式化输出savecount=nowtime+"\n"+text.get("0.0","end")with open(file_path+"\save.txt",'w') as fp:fp.write(savecount)tkinter.messagebox.showinfo('提示',"结果已保存")def history():if os.path.exists(file_path+"\save.txt"):with open(file_path+"\save.txt",'r') as fp:   historytxt=fp.read()tkinter.messagebox.showinfo('历史',historytxt)def helpinf():tkinter.messagebox.showinfo('帮助',"""1.输入您要统计的代码文件路径
2.输入您要统计的代码文件类型
3.保存功能只能保存上次查询的结果
快捷键:
F1                查看帮助
ENTE           提交
Alt-F4         退出
Control-s   保存""")def aboutinf():tkinter.messagebox.showinfo('关于',"您现在正在使用的是测试版本   by:田川")def out_save_xls(code_dict):if not text.get("0.0","end").strip(): #获取文本框内容,从开始到结束tkinter.messagebox.showwarning('提示',"还没有统计数据!")return Noneout_save.out_to_xls(code_dict)tkinter.messagebox.showinfo('提示',"结果已导出")menu=Menu(root)
submenu1=Menu(menu,tearoff=0)
menu.add_cascade(label='查看',menu=submenu1)
submenu1.add_command(label='历史',command=history)
submenu1.add_command(label='保存',command=save)
submenu1.add_command(label='导出',command=lambda :out_save_xls(code_dict))
submenu1.add_separator()
submenu1.add_command(label='退出', command=root.quit)
submenu2=Menu(menu,tearoff=0)
menu.add_cascade(label='帮助',menu=submenu2)
submenu2.add_command(label='查看帮助',command=helpinf)
submenu2.add_command(label='关于',command=aboutinf)
root.config(menu=menu)
#以上都是菜单栏的设置root.mainloop() #执行tk

code_count.py

#encoding=utf-8
import os,sys
import file_countdef code_count(path,file_types):if os.path.exists(path):os.chdir(path)else:#messagebox.showwarning("您输入的路径不存在!")print("您输入的路径不存在!")#sys.exit()files_path=[]file_types=file_types.split()line_count=0space_count=0annotation_count=0file_lines_dict=dict()for root,dirs,files in os.walk(path):for f in files:files_path.append(os.path.join(root,f))for file_path in files_path:#print(os.path.splitext(file_path)[1][1:])file_type=os.path.splitext(file_path)[1][1:]if file_type in file_types:if file_type.lower()=="java":line_num,space_num,annotation_num=file_count.count_javafile_lines(file_path)line_count+=line_numspace_count+=space_numannotation_count+=annotation_numfile_lines_dict[file_path]=line_num,space_num,annotation_numif file_type.lower()=="py":line_num,space_num,annotation_num=file_count.count_py_lines(file_path)line_count+=line_numspace_count+=space_numannotation_count+=annotation_numfile_lines_dict[file_path]=line_num,space_num,annotation_num#file_info=file_show(line_num,space_num,annotation_num)#print(file_info[0])return line_count,file_lines_dict,space_count,annotation_count

file_count.py

#encoding=utf-8
import osdef count_py_lines(file_path):line_count = 0space_count=0annotation_count=0flag =Truetry:fp = open(file_path,"r",encoding="utf-8")encoding_type="utf-8"for i in fp:passfp.close()except:#print(file_path)encoding_type="gbk"with open(file_path,"r",encoding=encoding_type,errors="ignore") as fp:#print(file_path)"""try:fp.read()except:fp.close()"""for line in fp:           if line.strip() == "":space_count+=1else:if line.strip().endswith("'''") and flag == False:annotation_count+=1#print(line)flag = Truecontinueif line.strip().endswith('"""') and flag == False:annotation_count+=1#print('结尾双引',line)flag = Truecontinueif flag == False:annotation_count+=1#print("z",line)continue  """if flag == False:annotation_count+=1print("z",line)"""if line.strip().startswith("#encoding") \or line.strip().startswith("#-*-"):line_count += 1elif line.strip().startswith('"""') and line.strip().endswith('"""') and line.strip() != '"""':annotation_count+=1#print(line)elif line.strip().startswith("'''") and line.strip().endswith("'''") and line.strip() != "'''":annotation_count+=1#print(line)elif line.strip().startswith("#"):annotation_count+=1#print(line)elif line.strip().startswith("'''") and flag == True:flag = Falseannotation_count+=1#print(line)elif line.strip().startswith('"""') and flag == True:flag = Falseannotation_count+=1#print('开头双引',line)else:line_count += 1return line_count,space_count,annotation_count#path=input("请输入您要统计的绝对路径:")
#file_types=input("请输入您要统计的文件类型:")#print("整个%s有%s类型文件%d个,共有%d行代码"%(path,file_types,len(code_dict),codes))
#print("代码最多的是%s,有%d行代码"%(max_code[1],max_code[0]))def count_javafile_lines(file_path):line_count = 0space_count=0annotation_count=0flag =True#read_type=''try:fp = open(file_path,"r",encoding="utf-8")encoding_type="utf-8"for i in fp:passfp.close()except:#print(file_path)encoding_type="gbk"with open(file_path,"r",encoding=encoding_type) as fp:#print(file_path)for line in fp:           if line.strip() == "":space_count+=1else:if line.strip().endswith("*/") and flag == False:flag = Trueannotation_count+=1continueif flag == False:annotation_count+=1continueelif line.strip().startswith('/*') and line.strip().endswith('*/'):annotation_count+=1elif line.strip().startswith('/**') and line.strip().endswith('*/'):annotation_count+=1                elif line.strip().startswith("//") and flag == True:flag = Falsecontinueelse:line_count += 1return line_count,space_count,annotation_count

out_save.py

#encoding=utf-8
import os,time
from openpyxl import Workbook
from openpyxl import load_workbookdef out_to_xls(file_dict):nowtime=time.strftime("%Y-%m-%d %H-%M-%S", time.localtime()) #获取当前时间并格式化输出file_path=os.path.dirname(__file__)if os.path.exists(file_path+'\out_save.xlsx'):#print("y")wb=load_workbook(file_path+'\out_save.xlsx')ws=wb.create_sheet(nowtime)ws['A1']='文件名' #增加表头ws['B1']='有效代码'ws['C1']='空白行数'ws['D1']='注释行数'for file_name,file_data in file_dict.items(): #循环得到的文件字典ws.append([file_name]+list(file_data)) #因为工作表的append方法只能添加一个list,所以把文件名和文件统计数据放在一个list里wb.save(file_path+'\out_save.xlsx') #把导出的内容保存到文件目录下else:#print("no")wb=Workbook() #创建一个工作簿ws=wb.create_sheet(nowtime,index=0) #新建名称为当前时间的sheet插在开头,方便做统计及记录ws['A1']='文件名' #增加表头ws['B1']='有效代码'ws['C1']='空白行数'ws['D1']='注释行数'for file_name,file_data in file_dict.items(): #循环得到的文件字典ws.append([file_name]+list(file_data)) #因为工作表的append方法只能添加一个list,所以把文件名和文件统计数据放在一个list里wb.remove(wb.get_sheet_by_name("Sheet"))wb.save(file_path+'\out_save.xlsx') #把导出的内容保存到文件目录下

本次更新:

  1. 修改导出功能
  2. 更新了当不输入路径和类型时点击提交按钮直接退出的问题

更新代码为:

  1. out_to_xls方法
#encoding=utf-8
import os,time
from openpyxl import Workbook
from openpyxl import load_workbookdef out_to_xls(file_dict):nowtime=time.strftime("%Y-%m-%d %H-%M-%S", time.localtime()) #获取当前时间并格式化输出file_path=os.path.dirname(__file__)if os.path.exists(file_path+'\out_save.xlsx'):#print("y")wb=load_workbook(file_path+'\out_save.xlsx')ws=wb.create_sheet(nowtime)ws['A1']='文件名' #增加表头ws['B1']='有效代码'ws['C1']='空白行数'ws['D1']='注释行数'for file_name,file_data in file_dict.items(): #循环得到的文件字典ws.append([file_name]+list(file_data)) #因为工作表的append方法只能添加一个list,所以把文件名和文件统计数据放在一个list里wb.save(file_path+'\out_save.xlsx') #把导出的内容保存到文件目录下else:#print("no")wb=Workbook() #创建一个工作簿ws=wb.create_sheet(nowtime,index=0) #新建名称为当前时间的sheet插在开头,方便做统计及记录ws['A1']='文件名' #增加表头ws['B1']='有效代码'ws['C1']='空白行数'ws['D1']='注释行数'for file_name,file_data in file_dict.items(): #循环得到的文件字典ws.append([file_name]+list(file_data)) #因为工作表的append方法只能添加一个list,所以把文件名和文件统计数据放在一个list里wb.remove(wb.get_sheet_by_name("Sheet"))wb.save(file_path+'\out_save.xlsx') #把导出的内容保存到文件目录下

python tkinter图形界面代码统计工具--更新相关推荐

  1. python图形界面代码_python tkinter图形界面代码统计工具(更新)

    本文为大家分享了python tkinter图形界面代码统计工具的更新版,供大家参考,具体内容如下 代码统计工具 修改了导出excel功能,把原来的主文件进行了拆分 code_count_window ...

  2. python图形统计代码_python tkinter图形界面代码统计工具

    本文为大家分享了python tkinter图形界面代码统计工具,供大家参考,具体内容如下 #encoding=utf-8 import os,sys,time from collections im ...

  3. 编写一个python程序、输出如下图形效果_Tkinter模块编写Python图形界面代码实例...

    本篇文章小编给大家分享一下Tkinter模块编写Python图形界面代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. 一.为何使用Tkinter ...

  4. 不是python中用于开发用户界面的第三方库-python界面 | Tkinter图形界面开发库

    0 写在前面 未经允许,不得转载,谢谢~~ 毕设要在现有的基础上做一个可视化的界面,所以趁机也学习一波如何用python实现图形界面的开发. 本文主要学习并整理了: 简要介绍用于python图形界面开 ...

  5. python打代码运行图形_利用aardio给python编写图形界面

    前阵子在用python写一些小程序,写完后就开始思考怎么给python程序配一个图形界面,毕竟控制台实在太丑陋了. 于是百度了下python的图形界面库,眼花缭乱的一整页,拣了几件有"特色& ...

  6. Python代码统计工具

    目录 Python代码统计工具 声明 一. 问题提出 二. 代码实现 三. 效果验证 Python代码统计工具 标签: Python 代码统计 声明 本文将对<Python实现C代码统计工具(一 ...

  7. python界面不同按钮实现不同功能-python tkinter实现界面切换的示例代码

    跳转实现思路 主程序相当于桌子: import tkinter as tk root = tk.Tk() 而不同的Frame相当于不同的桌布: face1 = tk.Frame(root) face2 ...

  8. python 代码行数统计工具_使用Python设计一个代码统计工具

    问题 设计一个程序,用于统计一个项目中的代码行数,包括文件个数,代码行数,注释行数,空行行数.尽量设计灵活一点可以通过输入不同参数来统计不同语言的项目,例如: # type用于指定文件类型 pytho ...

  9. python的电脑推荐_推荐8款常用的Python GUI图形界面开发框架

    作为Python开发者,你迟早都会用到图形用户界面来开发应用.本文将推荐一些 Python GUI 框架,希望对你有所帮助,如果你有其他更好的选择,欢迎在评论区留言. Python 的 UI 开发工具 ...

最新文章

  1. 实操教程|详细记录solov2的ncnn实现和优化
  2. 10 个 Linux 中方便的 Bash 别名
  3. 原生js已载入就执行函数_手写CommonJS 中的 require函数
  4. Elasticsearch如何关掉服务
  5. 漫步者蓝牙驱动_2020年知乎最受欢迎的高性价比真无线蓝牙耳机推荐,轻松选择蓝牙耳机(9月最新)!...
  6. Kubernetes引发“军备赛”,K8s真是企业生存的关键吗
  7. C#LeetCode刷题之#657-机器人能否返回原点(Robot Return to Origin)
  8. 复古多变“格子控”混搭 夏季继续魅力四射
  9. 关系查询处理 查询优化 论文_论文导读基于查询负载的分布式RDF图分割和分配...
  10. Spring boot 配置array,list,map
  11. HashMap 的数据结构
  12. IOS_多线程_GET_POST_AFN_上传下载_视频播放
  13. 机械制造作业考研题目答案分享——定位误差及其计算
  14. 华为鸿蒙智慧屏和手机,【荣耀智慧屏评测】鸿蒙初体验:荣耀智慧屏跨系统交互构建新生态(全文)_荣耀 智慧屏_手机评测-中关村在线...
  15. 小小摩尔福斯之网络侦探
  16. [爬虫笔记01] Ajax爬取今日头条文章
  17. 游戏经典题目之十字激光炮
  18. 问题记录之——windows10系统蓝牙失灵
  19. 某大厂程序员炫耀:来新加坡后,每天最多工作五六个小时,家庭年收入150万人民币,已躺平!...
  20. openlayers加载百度地图作为底图坐标偏移的解决办法

热门文章

  1. 屏幕小于6英寸的手机_小米首款Android Go手机曝光:价格低廉屏幕小于6英寸
  2. 测试驱动开发在软件开发中的重要性
  3. 预计保持30%增速,2022年酒店该如何发力亲子游市场?
  4. 为什么启动引导加载到内存时在0x7c00
  5. Linux 系统管理 : userdel 命令详解
  6. 1099:第n小的质数
  7. 为什么pygame下载的时候会一直卡在元数据启动状态
  8. 苹果官方购置iPad用户将获1100元退款
  9. 阶乘求和(应用函数方法求和)
  10. 【华为云-玩转云耀云服务器HECS】使用HECS搭建WordPress博客平台