1. 程式人生 > 程式設計 >python tkinter圖形介面程式碼統計工具(更新)

python tkinter圖形介面程式碼統計工具(更新)

本文為大家分享了python tkinter圖形介面程式碼統計工具的更新版,供大家參考,具體內容如下

程式碼統計工具

修改了匯出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_count

root= Tk()
root.title("有效程式碼統計工具") #介面的title

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) #刪除顯示文字框中,原有的內容
  
  global code_dict
  for 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,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="型別:",fg="blue").grid(row=1,pady=5)
e1= Entry(frame,foreground = 'blue',font = ('Helvetica','12')) #建立文字輸入框
e2= Entry(frame,'12','bold'))
e1.grid(row=0,column=1,sticky=W) #佈置文字輸入框
e2.grid(row=1,sticky=W,)
labeltitle=Label(frame,text="輸入多個檔案路徑請使用';'分割",10,'bold'),fg="red")
labeltitle.grid(row=2,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=" 提交 ",13),width=10,command=show).grid(row=3,column=0,padx=15,pady=5) #建立按鈕
button2= Button(frame,text=" 退出 ",command=root.quit).grid(row=3,pady=5)
#self.hi_there.pack()
text = scrolledtext.ScrolledText(frame,width=40,height=10,15)) #建立可滾動的文字顯示框
text.grid(row=4,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(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","還沒有統計資料!")
    return None
  out_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_count

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=file_count.count_javafile_lines(file_path)
        line_count+=line_num
        space_count+=space_num
        annotation_count+=annotation_num
        file_lines_dict[file_path]=line_num,annotation_num
      if file_type.lower()=="py":
        line_num,annotation_num=file_count.count_py_lines(file_path)
        line_count+=line_num
        space_count+=space_num
        annotation_count+=annotation_num
        file_lines_dict[file_path]=line_num,annotation_num
        #file_info=file_show(line_num,annotation_num)
        #print(file_info[0])
  return line_count,file_lines_dict,space_count,annotation_count

file_count.py

#encoding=utf-8
import os

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,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,annotation_count

#path=input("請輸入您要統計的絕對路徑:")
#file_types=input("請輸入您要統計的檔案型別:")

#print("整個%s有%s型別檔案%d個,共有%d行程式碼"%(path,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,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,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,annotation_count

out_save.py

#encoding=utf-8
import os,time
from openpyxl import Workbook
from openpyxl import load_workbook

def 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,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') #把匯出的內容儲存到檔案目錄下

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。