python tkinter图形界面代码统计工具
作者:hichcock_tian 发布时间:2021-01-29 15:21:39
标签:python,tkinter,代码统计
本文为大家分享了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!
来源:https://blog.csdn.net/hichcock_tian/article/details/87102446


猜你喜欢
- 对于添加一个文件的路径我用的第一个方法就是sys.path.append()博主比较懒,就直接截图了啊对于上级文件路径和再上一级的路径可以直
- 目标在本章中,将学习使用kNN来构建基本的OCR应用程使用OpenCV自带的数字和字母数据集手写数字的OCR目标是构建一个可以读取手写数字的
- 第五个页面name="changenick.php" <? include &q
- 如何用Cookie进行登录验证?很简单,看看这两个文件:login.htm请注册登录随风起舞<FORM ACTION=&qu
- 1、在命令行里停止MySQL服务:net stop mysql2、修改mysql安装目录下的my,ini,将default-ch
- 内容摘要:图片随机显示是一个应用非常广泛的技巧。比如随机banner的显示,当你进入一个网站时它的banner总是不同的,或者总有内容不同的
- 之前用Python 2.7版本的httplib做接口测试时,运行代码都是正常的,最近开始用Python 3.3之后,再去看以前的代码,发现i
- 1. 文件夹结构指定文件夹:E:/Code/Python/test指定文件:test.txt指定文件夹下的目录及文件:文件夹a:a.txtt
- Pygame精灵和碰撞检测今天来看看python最出名的游戏库pygame。学习两个名词:精灵和碰撞检测。精灵英文字母是Sprite。Spr
- join的写法如果用left join 左边的表一定是驱动表吗?两个表的join包含多个条件的等值匹配,都要写道on还是只把一个写到on,其
- 一、注意你的Python版本Python官方网站为http://www.python.org/,当前最新稳定版本为3.6.5,在3.0版本时
- 前言wx.gird.Gird是实现类似excel表格的库,扩展面很广,本文讲述它添加按钮,按钮响应的内容实现效果图如下:本文基于wxPyth
- 本教程为大家分享了Linux安装MySQL详细步骤,供大家参考,具体内容如下第一步: 下载MySQL安装包进入mysql官网,进入downl
- 废话不多说,我就直接上代码让大家看看吧!#!/usr/bin/env python# -*- coding: utf-8 -*-# @Fil
- 引言故事从好多年前说起。想必大家也听说过数据库单表建议最大2kw条数据这个说法。如果超过了,性能就会下降得比较厉害。巧了。我也听说过。但我不
- 下面写一个给大家做参考啊 create procedure sp_find(pfind varchar(500) BEGIN DECLAR
- 学习目的 学会SQL中的占位符用法 在鲸鱼这几天忙死了,好几天没写了,真对不起各位。这几天让XHTML闹得不开心,虽然以前也知道这个,但没太
- 昨天晚上才发现已经出了jQuery的1.3版本,于是下载下来,把原来一个兄弟翻译的1.2.6的文档移植到了1.3中,点击这里可
- 我的设备上每秒将2000条数据插入数据库,2个设备总共4000条,当在程序里面直接用insert语句插入时,两个设备同时插入大概总共能插入约
- 有时候我们需要查看mysql的版本信息,那么就可以参考下面的方法1、使用命令行模式进入mysql会看到最开始的提示符在命令行登录mysql,