侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   210

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

#encoding=utf-8import os,sys,timefrom collections import defaultdictfrom tkinter import *import tkinter.messageboxfrom tkinter import ttkfrom tkinter import scrolledtextroot= Tk()root.title("有效代码统计工具") #界面的titledef 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_countdef 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!

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


  • 上一条:
    python3使用GUI统计代码量
    下一条:
    Python自动生成代码 使用tkinter图形化操作并生成代码框架
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客