Little_tools/CodeCalc.py
2025-01-14 11:19:32 +08:00

75 lines
2.6 KiB
Python

import os
import tkinter as tk
from tkinter import filedialog, messagebox, font
def count_lines_and_comments(directory, text_widget):
total_code_lines = 0
total_comment_lines = 0
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
code_lines = 0
comment_lines = 0
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
stripped_line = line.strip()
if not stripped_line: # Skip empty lines
continue
if stripped_line.startswith('#'):
comment_lines += 1
else:
code_lines += 1
total_code_lines += code_lines
total_comment_lines += comment_lines
text_widget.insert(tk.END, f"{file_path} - 代码行数: {code_lines}, 注释行数: {comment_lines}\n")
text_widget.insert(tk.END, f"\n'{directory}': 总代码行数: {total_code_lines}, 总注释行数: {total_comment_lines}\n")
def browse_folder():
folder_path = filedialog.askdirectory()
entry_path.delete(0, tk.END)
entry_path.insert(0, folder_path)
def on_calculate():
directory = entry_path.get()
if not directory:
directory = 'E:\\Self-Tool-Code\\Pybot'
if not os.path.exists(directory):
messagebox.showerror("错误", "指定的目录不存在")
return
text_output.delete(1.0, tk.END) # 清空文本框
count_lines_and_comments(directory, text_output)
# 创建主窗口
root = tk.Tk()
root.title("代码行数统计工具")
# 设置字体为宋体
custom_font = font.Font(family="宋体", size=12)
# 创建路径输入框和标签
label_path = tk.Label(root, text="路径:", font=custom_font)
label_path.grid(row=0, column=0, padx=10, pady=10)
entry_path = tk.Entry(root, width=50, font=custom_font)
entry_path.grid(row=0, column=1, padx=10, pady=10)
entry_path.insert(0, "E:\\Self-Tool-Code\\Pybot")
# 创建浏览文件夹按钮
button_browse = tk.Button(root, text="浏览", command=browse_folder, font=custom_font)
button_browse.grid(row=0, column=2, padx=10, pady=10)
# 创建按钮
calculate_button = tk.Button(root, text="计算", command=on_calculate, font=custom_font)
calculate_button.grid(row=1, column=0, columnspan=3, pady=10)
# 创建文本框用于显示输出
text_output = tk.Text(root, width=80, height=20, font=custom_font)
text_output.grid(row=2, column=0, columnspan=3, padx=10, pady=10)
# 运行主循环
root.mainloop()