# 用tkinter实现文本内容统计程序


问题描述

我们需要创建一个程序,用户输入文本内容,程序统计所有单词数量并显示。用户输入文本后程序读取内容,统计单词,并输出结果。程序需要使用tkinter库创建图形界面,支持输入文本和统计结果。

输入输出示例

输入:hello world
输出:hello:1, world:1

思路分析

该问题需要实现以下能力:
1. 使用tkinter创建图形界面
2. 读取文件内容(通过tkinter的文件读取功能)
3. 统计文本中的单词数量
4. 显示统计结果

代码实现

import tkinter as tk

def count_words(text):
    words = text.split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    result = " ".join([f'{word}: {count}' for word, count in counts.items()])
    return result

def main():
    root = tk.Tk()
    root.title("Word Counter")

    text_box = tk.Entry(root, width=40)
    text_box.pack()

    def count_words():
        text = text_box.get()
        result = count_words(text)
        print(result)

    count_button = tk.Button(root, text="Count Words", command=count_words)
    count_button.pack()

    root.mainloop()

if __name__ == "__main__":
    main()

总结

该程序使用tkinter创建图形界面,用户输入文本内容后程序统计并输出单词数量。核心知识点包括文件操作和数据结构统计,难度适中,适合1~3天完成。代码规范良好,支持输入文本和输出结果,包含解释性注释。