🧮 用 Python (Tkinter) 构建桌面词数统计应用

发布: (2025年12月30日 GMT+8 10:18)
7 min read
原文: Dev.to

Source: Dev.to

✨ 功能

  • 📊 实时 单词、字符、句子 & 行计数
  • 🔍 关键词密度 计算
  • 估计阅读时间(200 WPM)
  • 📂 打开 & 保存.txt 文件
  • 🌙 明暗模式切换
  • 🧹 清除文本(需确认)
  • ❓ 内置 帮助对话框
  • 💻 完全 离线 且跨平台

🧰 技术栈

  • Python 3
  • Tkinter(GUI)
  • ttk(主题小部件)
  • sv‑ttk(现代明暗主题)
  • threading(非阻塞更新)

📦 要求

只需要一个外部依赖:

pip install sv-ttk

🏗️ 应用架构

应用被划分为逻辑部分:

  1. Helpers – 状态更新 & 资源路径
  2. Core Logic – 文本分析 & 关键词密度
  3. UI Sections – 文本输入、统计、操作
  4. Theme Engine – 明暗模式切换
  5. File Operations – 打开、保存、清除

这样可以保持代码的可读性和可扩展性。

🧠 文本分析工作原理

指标方法
单词split()
字符len(text)
字符(不含空格)删除空格和换行后,使用 len()
句子统计 ., !, ? 的出现次数
阅读时间words / 200 WPM(四舍五入,最少 1 分钟)
关键词密度(keyword occurrences / total words) * 100

所有更新都会在您输入时实时显示。

🧩 完整源代码

将以下所有内容复制到 wordcounter_pro.py 文件中并运行它。

import sys
import os
import threading
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sv_ttk

# =========================
# Helpers
# =========================
def resource_path(file_name):
    base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, file_name)

def set_status(msg):
    status_var.set(msg)
    root.update_idletasks()

# =========================
# App Setup
# =========================
root = tk.Tk()
root.title("WordCounter Pro")
root.geometry("1050x650")

sv_ttk.set_theme("light")

# =========================
# Globals
# =========================
dark_mode_var = tk.BooleanVar(value=False)

stats_vars = {
    "words": tk.StringVar(value="0"),
    "characters": tk.StringVar(value="0"),
    "characters_no_space": tk.StringVar(value="0"),
    "lines": tk.StringVar(value="0"),
    "sentences": tk.StringVar(value="0"),
    "reading_time": tk.StringVar(value="0 min"),
}

keyword_var = tk.StringVar()
keyword_density_var = tk.StringVar(value="0%")

# =========================
# Theme Toggle
# =========================
def toggle_theme():
    style.theme_use("clam")
    bg = "#2E2E2E" if dark_mode_var.get() else "#FFFFFF"
    fg = "white" if dark_mode_var.get() else "black"

    root.configure(bg=bg)
    for w in ["TFrame", "TLabel", "TLabelframe", "TLabelframe.Label", "TCheckbutton"]:
        style.configure(w, background=bg, foreground=fg)

    text_area.configure(
        bg="#1e1e1e" if dark_mode_var.get() else "white",
        fg="white" if dark_mode_var.get() else "black",
        insertbackground="white" if dark_mode_var.get() else "black"
    )

    set_status(f"Theme switched to {'Dark' if dark_mode_var.get() else 'Light'} mode")

# =========================
# Core Logic
# =========================
def count_text():
    content = text_area.get("1.0", tk.END).strip()

    if not content:
        for key in stats_vars:
            stats_vars[key].set("0" if key != "reading_time" else "0 min")
        keyword_density_var.set("0%")
        return

    words_list = content.split()
    words = len(words_list)
    characters = len(content)
    characters_no_space = len(content.replace(" ", "").replace("\n", ""))
    lines = len(content.splitlines())
    sentences = sum(content.count(x) for x in ".!?")

    reading_minutes = max(1, round(words / 200))
    stats_vars["reading_time"].set(f"{reading_minutes} min")

    stats_vars["words"].set(words)
    stats_vars["characters"].set(characters)
    stats_vars["characters_no_space"].set(characters_no_space)
    stats_vars["lines"].set(lines)
    stats_vars["sentences"].set(sentences)

    keyword = keyword_var.get().strip().lower()
    if keyword:
        occurrences = sum(1 for w in words_list if w.lower() == keyword)
        density = (occurrences / words) * 100
        keyword_density_var.set(f"{density:.2f}%")
    else:
        keyword_density_var.set("0%")

    set_status("Text analyzed")

def delayed_count(event=None):
    threading.Timer(0.1, count_text).start()

# =========================
# File Operations
# =========================
def open_file():
    path = filedialog.askopenfilename(
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
    )
    if not path:
        return
    try:
        with open(path, "r", encoding="utf-8") as f:
            text_area.delete("1.0", tk.END)
            text_area.insert("1.0", f.read())
        count_text()
        set_status(f"Loaded: {os.path.basename(path)}")
    except Exception as e:
        messagebox.showerror("Error", str(e))

def save_file():
    path = filedialog.asksaveasfilename(
        defaultextension=".txt",
        filetypes=[("Text Files", "*.txt")]
    )
    if not path:
        return
    try:
        with open(path, "w", encoding="utf-8") as f:
            f.write(text_area.get("1.0", tk.END))

set_status(f”Saved to {path}”) except Exception as e: messagebox.showerror(“Error”, str(e))

def clear_text(): if messagebox.askyesno(“Clear”, “Clear all text?”): text_area.delete(“1.0”, tk.END) count_text() set_status(“Text cleared”)

=========================

Help Window

=========================

def show_help(): win = tk.Toplevel(root) win.title(“WordCounter Pro - Help”) win.geometry(“480x360”) win.configure(bg=“#2e2e2e”) win.resizable(False, False) win.transient(root) win.grab_set()

frame = tk.Frame(win, bg="#2e2e2e")
frame.pack(fill="both", expand=True, padx=12, pady=12)

text = tk.Text(
    frame,
    bg="#2e2e2e",
    fg="white",
    insertbackground="white",
    wrap="word",
    relief="flat",
    borderwidth=0,
)
text.pack(fill="both", expand=True)

help_content = (
    "WordCounter Pro helps you analyse text quickly.\n\n"
    "• Type or paste text into the main area.\n"
    "• Statistics update live.\n"
    "• Use the keyword field to see density.\n"
    "• Open/Save files via the menu.\n"
    "• Toggle Light/Dark mode with the checkbox.\n"
    "• Clear text with confirmation.\n"
)
text.insert("1.0", help_content)
text.configure(state="disabled")

=========================

UI Construction

=========================

style = ttk.Style() style.theme_use(“clam”)

Top frame – menu & theme toggle

top_frame = ttk.Frame(root, padding=10) top_frame.pack(fill=“x”)

menu_bar = tk.Menu(root) file_menu = tk.Menu(menu_bar, tearoff=0) file_menu.add_command(label=“Open”, command=open_file) file_menu.add_command(label=“Save As…”, command=save_file) file_menu.add_separator() file_menu.add_command(label=“Exit”, command=root.quit) menu_bar.add_cascade(label=“File”, menu=file_menu)

help_menu = tk.Menu(menu_bar, tearoff=0) help_menu.add_command(label=“Help”, command=show_help) menu_bar.add_cascade(label=“Help”, menu=help_menu)

root.config(menu=menu_bar)

theme_check = ttk.Checkbutton( top_frame, text=“Dark Mode”, variable=dark_mode_var, command=toggle_theme, ) theme_check.pack(side=“right”)

Main content – text area & stats

main_pane = ttk.PanedWindow(root, orient=tk.HORIZONTAL) main_pane.pack(fill=“both”, expand=True, padx=10, pady=10)

Text input

text_frame = ttk.Labelframe(main_pane, text=” Text Input ”) text_frame.pack(fill=“both”, expand=True, side=“left”, padx=5, pady=5)

text_area = tk.Text( text_frame, wrap=“word”, undo=True, font=(“Helvetica”, 12), relief=“flat”, borderwidth=2, ) text_area.pack(fill=“both”, expand=True, padx=5, pady=5) text_area.bind("", delayed_count)

Stats panel

stats_frame = ttk.Labelframe(main_pane, text=” Statistics ”) stats_frame.pack(fill=“both”, expand=False, side=“right”, padx=5, pady=5)

def add_stat(label, var): row = ttk.Frame(stats_frame) row.pack(fill=“x”, pady=2) ttk.Label(row, text=label + ”:“).pack(side=“left”) ttk.Label(row, textvariable=var).pack(side=“right”)

add_stat(“Words”, stats_vars[“words”]) add_stat(“Characters”, stats_vars[“characters”]) add_stat(“Characters (no spaces)”, stats_vars[“characters_no_space”]) add_stat(“Lines”, stats_vars[“lines”]) add_stat(“Sentences”, stats_vars[“sentences”]) add_stat(“Reading Time”, stats_vars[“reading_time”])

Keyword density

keyword_frame = ttk.Labelframe(stats_frame, text=” Keyword Density ”) keyword_frame.pack(fill=“x”, pady=8, padx=4)

ttk.Label(keyword_frame, text=“Keyword:“).grid(row=0, column=0, sticky=“w”, padx=2, pady=2) keyword_entry = ttk.Entry(keyword_frame, textvariable=keyword_var) keyword_entry.grid(row=0, column=1, sticky=“e”, padx=2, pady=2)

ttk.Label(keyword_frame, text=“Density:“).grid(row=1, column=0, sticky=“w”, padx=2, pady=2) ttk.Label(keyword_frame, textvariable=keyword_density_var).grid(row=1, column=1, sticky=“e”, padx=2, pady=2)

Bottom status bar

status_var = tk.StringVar(value=

"Ready")
status_bar = ttk.Label(root, textvariable=status_var, relief="sunken", anchor="w")
status_bar.pack(fill="x", side="bottom")

# Initial theme sync
toggle_theme()

root.mainloop()

WordCounter Pro – Tkinter UI(Python)

# =========================
# Help Window
# =========================
def show_help():
    help_win = tk.Toplevel(root)
    help_win.title("Quick Help")
    help_win.geometry("420x340")
    help_win.resizable(False, False)

    text = tk.Text(
        help_win,
        bg="#2e2e2e",
        fg="#f0f0f0",
        font=("Segoe UI", 11),
        wrap="word",
        borderwidth=0
    )
    text.pack(fill="both", expand=True)

    help_text = """📊 WordCounter Pro — Quick Help

• Type or paste text to see live statistics
• Counts words, characters, sentences, and lines
• Enter a keyword to calculate density (%)
• Reading time based on 200 words per minute
• Open and save .txt files
• Toggle Dark Mode for comfort

All processing is done locally.
"""
    text.insert("1.0", help_text)
    text.config(state="disabled")

# =========================
# Styles
# =========================
style = ttk.Style()
style.theme_use("clam")
style.configure(
    "Action.TButton",
    font=("Segoe UI", 11, "bold"),
    foreground="white",
    background="#4CAF50",
    padding=8
)
style.map("Action.TButton", background=[("active", "#45a049")])

# =========================
# Status Bar
# =========================
status_var = tk.StringVar(value="Ready")
ttk.Label(root, textvariable=status_var, anchor="w").pack(side=tk.BOTTOM, fill="x")

# =========================
# Main UI
# =========================
main = ttk.Frame(root, padding=20)
main.pack(expand=True, fill="both")

ttk.Label(main, text="WordCounter Pro", font=("Segoe UI", 22, "bold")).pack()
ttk.Label(main, text="Advanced word & text analysis tool",
          font=("Segoe UI", 11)).pack(pady=(0, 10))

# =========================
# Text Area
# =========================
text_frame = ttk.LabelFrame(main, text="Text Input", padding=10)
text_frame.pack(fill="both", pady=10)

text_area = tk.Text(
    text_frame,
    font=("Segoe UI", 11),
    wrap="word",
    height=10
)
text_area.pack(fill="both")
text_area.bind("", delayed_count)

# =========================
# Statistics
# =========================
stats_frame = ttk.LabelFrame(main, text="Statistics", padding=15)
stats_frame.pack(fill="x", pady=8)

for i, (label, var) in enumerate(stats_vars.items()):
    ttk.Label(stats_frame, text=label.replace("_", " ").title() + ":",
              font=("Segoe UI", 10, "bold")).grid(row=0, column=i * 2, padx=4, sticky="e")
    ttk.Label(stats_frame, textvariable=var,
              font=("Segoe UI", 10)).grid(row=0, column=i * 2 + 1, padx=6, sticky="w")

# =========================
# Keyword Density
# =========================
keyword_frame = ttk.LabelFrame(main, text="Keyword Density", padding=12)
keyword_frame.pack(fill="x", pady=8)

ttk.Label(keyword_frame, text="Keyword:",
          font=("Segoe UI", 10, "bold")).pack(side="left", padx=(0, 6))

keyword_entry = ttk.Entry(keyword_frame, textvariable=keyword_var, width=22)
keyword_entry.pack(side="left")
keyword_entry.bind("", delayed_count)

ttk.Label(keyword_frame, text="Density:",
          font=("Segoe UI", 10, "bold")).pack(side="left", padx=(15, 6))

ttk.Label(keyword_frame, textvariable=keyword_density_var,
          font=("Segoe UI", 10)).pack(side="left")

# =========================
# Actions
# =========================
actions = ttk.Frame(main)
actions.pack(pady=12)

ttk.Button(actions, text="📂 Open", command=open_file,
           style="Action.TButton").pack(side="left", padx=6)
ttk.Button(actions, text="💾 Save", command=save_file,
           style="Action.TButton").pack(side="left", padx=6)
ttk.Button(actions, text="🧹 Clear", command=clear_text,
           style="Action.TButton").pack(side="left", padx=6)
ttk.Button(actions, text="❓ Help", command=show_help,
           style="Action.TButton").pack(side="left", padx=6)

ttk.Checkbutton(
    actions,
    text="Dark Mode",
    variable=dark_mode_var,
    command=toggle_theme
).pack(side="left", padx=14)

# =========================
# Run App
# ========```

=================
root.mainloop()

🚀 扩展想法

  • 导出统计数据为 CSV
  • 高亮关键字出现次数
  • 实时可读性评分
  • 使用 PyInstaller 打包为 .exe
  • 添加拖放文件加载

🧠 最后思考

Tkinter 不一定要显得过时。使用 ttk + sv‑ttk,你可以完全用 Python 快速构建现代且实用的桌面工具。

如果你喜欢本篇内容,欢迎:

  • Fork 它
  • 扩展它
  • 将其打包成桌面应用

祝构建愉快! 🛠️

Back to Blog

相关文章

阅读更多 »