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


Posted in Python onSeptember 18, 2019

本文为大家分享了python tkinter图形界面代码统计工具,供大家参考,具体内容如下

#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

root= Tk()
root.title("有效代码统计工具") #界面的title

def 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=0
 space_count=0
 annotation_count=0
 file_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=count_javafile_lines(file_path)
    line_count+=line_num
    space_count+=space_num
    annotation_count+=annotation_num
    file_lines_dict[file_path]=line_num,space_num,annotation_num
   if file_type.lower()=="py":
    line_num,space_num,annotation_num=count_py_lines(file_path)
    line_count+=line_num
    space_count+=space_num
    annotation_count+=annotation_num
    file_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
 
def count_py_lines(file_path):
 line_count = 0
 space_count=0
 annotation_count=0
 flag =True
 try:
  fp = open(file_path,"r",encoding="utf-8")
  encoding_type="utf-8"
  for i in fp:
   pass
  fp.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+=1
   else:
    if line.strip().endswith("'''") and flag == False:
     annotation_count+=1
     #print(line)
     flag = True
     continue
    if line.strip().endswith('"""') and flag == False:
     annotation_count+=1
     #print('结尾双引',line)
     flag = True
     continue
    if flag == False:
     annotation_count+=1
     #print("z",line)
     continue 
    """if flag == False:
     annotation_count+=1
     print("z",line)"""
    if line.strip().startswith("#encoding") \
      or line.strip().startswith("#-*-"):
     line_count += 1
    elif 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 = False
     annotation_count+=1
     #print(line)
    elif line.strip().startswith('"""') and flag == True:
     flag = False
     annotation_count+=1
     #print('开头双引',line)
    else:
     line_count += 1
 return 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 = 0
 space_count=0
 annotation_count=0
 flag =True
 #read_type=''
 try:
  fp = open(file_path,"r",encoding="utf-8")
  encoding_type="utf-8"
  for i in fp:
   pass
  fp.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+=1
   else:
    if line.strip().endswith("*/") and flag == False:
     flag = True
     annotation_count+=1
     continue
    if flag == False:
     annotation_count+=1
     continue
    elif line.strip().startswith('/*') and line.strip().endswith('*/'):
     annotation_count+=1
    elif line.strip().startswith('/**') and line.strip().endswith('*/'):
     annotation_count+=1    
    elif line.strip().startswith("//") and flag == True:
     flag = False
     continue
    else:
     line_count += 1
 return line_count,space_count,annotation_count

def show(): #当按钮被点击,就调用这个方法
 pathlist=e1.get() #调用get()方法得到在文本框中输入的内容
 file_types=e2.get().lower()

 file_types_list=["py","java"]
 
 if not pathlist:
  tkinter.messagebox.showwarning('提示',"请输入文件路径!")
  return None
 if 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 None

 text.delete(1.0,END) #删除显示文本框中,原有的内容
 
 for path in pathlist.split(";"):
  path=path.strip()
  codes,code_dict,space,annotation=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) #创建标签
label= 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)

hi_there= Button(frame ,text=" 提交 ",font=("宋体",13),width=10,command=show).grid(row=3,column=0,padx=15,pady=5) #创建按钮
hi_there= 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 None
 savecount=''
 nowtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #获取当前时间并格式化输出
 savecount=nowtime+"\n"+text.get("0.0","end")
 with open("e:\\save.txt",'w') as fp:
  fp.write(savecount)
 tkinter.messagebox.showinfo('提示',"结果已保存")

def history():
 if os.path.exists("e:\\save.txt"):
  with open("e:\\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:田川")

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_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)
#以上都是菜单栏的设置
"""
def caidan(root):
 menu=tkinter.Menu(root)
 submenu1=tkinter.Menu(menu,tearoff=0)
 menu.add_cascade(label='查看',menu=submenu1)
 submenu2 = tkinter.Menu(menu, tearoff=0)
 submenu2.add_command(label='复制')
 submenu2.add_command(label='粘贴')
 menu.add_cascade(label='编辑',menu=submenu2)
 submenu = tkinter.Menu(menu, tearoff=0)
 submenu.add_command(
 ='查看帮助')
 submenu.add_separator()
 submenu.add_command(label='关于计算机')
 menu.add_cascade(label='帮助',menu=submenu)
 root.config(menu=menu)

caidan(root)"""
root.mainloop() #执行tk!

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

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

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

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

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
如何搜索查找并解决Django相关的问题
Jun 30 Python
Python文档生成工具pydoc使用介绍
Jun 02 Python
Python多线程爬虫简单示例
Mar 04 Python
Python用Bottle轻量级框架进行Web开发
Jun 08 Python
Python爬取qq music中的音乐url及批量下载
Mar 23 Python
谈谈python中GUI的选择
Mar 01 Python
Python学习笔记之open()函数打开文件路径报错问题
Apr 28 Python
Flask框架钩子函数功能与用法分析
Aug 02 Python
python 画条形图(柱状图)实例
Apr 24 Python
不到20行实现Python代码即可制作精美证件照
Apr 24 Python
Python DataFrame使用drop_duplicates()函数去重(保留重复值,取重复值)
Jul 20 Python
详解OpenCV获取高动态范围(HDR)成像
Apr 29 Python
Python自动生成代码 使用tkinter图形化操作并生成代码框架
Sep 18 #Python
Python 元组操作总结
Sep 18 #Python
python sorted函数的小练习及解答
Sep 18 #Python
python 默认参数相关知识详解
Sep 18 #Python
python连接PostgreSQL数据库的过程详解
Sep 18 #Python
Python传递参数的多种方式(小结)
Sep 18 #Python
余弦相似性计算及python代码实现过程解析
Sep 18 #Python
You might like
用php获取远程图片并把它保存到本地的代码
2008/04/07 PHP
常用的PHP数据库操作方法(MYSQL版)
2011/06/08 PHP
php设计模式 Bridge (桥接模式)
2011/06/26 PHP
php单态设计模式(单例模式)实例
2014/11/18 PHP
LINUX下PHP程序实现WORD文件转化为PDF文件的方法
2016/05/13 PHP
javascript Prototype 对象扩展
2009/05/15 Javascript
javaScript 删除字符串空格多种方法小结
2012/10/24 Javascript
jQuery的text()方法用法分析
2014/12/20 Javascript
JavaScript构造函数详解
2015/12/27 Javascript
深入学习jQuery Validate表单验证(二)
2016/01/18 Javascript
js删除数组元素、清空数组的简单方法(必看)
2016/07/27 Javascript
Bootstrap CSS布局之列表
2016/12/15 Javascript
详解JS中定时器setInterval和setTImeout的this指向问题
2017/01/06 Javascript
jQuery实现字体颜色渐变效果的方法
2017/03/29 jQuery
node.js程序作为服务并在windows下开机自启动(用forever)
2017/03/29 Javascript
AngularJS $http模块POST请求实现
2017/04/08 Javascript
jQuery EasyUI结合zTree树形结构制作web页面
2017/09/01 jQuery
浅谈Vue2.0中v-for迭代语法的变化(key、index)
2018/03/06 Javascript
vue的diff算法知识点总结
2018/03/29 Javascript
Node.js文件编码格式的转换的方法
2018/04/27 Javascript
vue 项目build错误异常的解决方法
2019/04/22 Javascript
详解vue-cli中使用rem,vue自适应
2019/05/06 Javascript
webpack打包优化的几个方法总结
2020/02/10 Javascript
Python实现的数据结构与算法之快速排序详解
2015/04/22 Python
在Django的URLconf中使用命名组的方法
2015/07/18 Python
Django的URLconf中使用缺省视图参数的方法
2015/07/18 Python
python 安装virtualenv和virtualenvwrapper的方法
2017/01/13 Python
python3模块smtplib实现发送邮件功能
2018/05/22 Python
python函数修饰符@的使用方法解析
2019/09/02 Python
Python与C/C++的相互调用案例
2021/03/04 Python
请问如下代码执行后a和b的值分别是什么
2016/05/05 面试题
优秀员工自荐信范文
2013/10/05 职场文书
大学生开西餐厅创业计划书
2014/02/01 职场文书
2015年个人审计工作总结
2015/04/07 职场文书
小学生勤俭节约倡议书
2015/04/29 职场文书
Python matplotlib多个子图绘制整合
2022/04/13 Python