返回首页

Python 中的 CRUD:使用 Tkinter 和 JSON 创建任务管理器

通过创建桌面任务管理器来实现 Python 中 CRUD 操作的实用指南。本文涵盖使用 Tkinter 构建图形界面、使用 JSON 进行数据存储,以及面向对象编程基础。

Python 中创建 CRUD 应用程序:从零开始的任务管理器
Advertisement 728x90

实战CRUD指南:用Python和Tkinter构建任务管理器

CRUD(创建、读取、更新、删除)是数据操作的核心模式。本指南通过构建一个桌面任务管理器,来实际应用这一模式。我们将使用Python、Tkinter和JSON进行数据存储。非常适合想巩固面向对象编程基础、文件处理和GUI开发的开发者。

应用架构与环境搭建

应用将放在单个app.py文件中。我们用JSON存储数据——对于这类项目简单高效。每项任务是一个字典,包含id(唯一标识)、text(描述)和completed(完成状态)。所有任务存入列表,并序列化为tasks.json

确保安装Python 3.6或更高版本。Tkinter内置,无需额外安装。新建项目文件夹,在IDE中打开。

Google AdInline article slot

数据模型与JSON处理

首先实现加载和保存数据的函数——这是读取和更新CRUD操作的基础。

import json
import os

TASKS_FILE = "tasks.json"

def load_tasks():
    """从JSON文件加载任务。"""
    if not os.path.exists(TASKS_FILE):
        return []
    with open(TASKS_FILE, "r", encoding="utf-8") as f:
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return []

def save_tasks(tasks):
    """将任务列表保存到JSON文件。"""
    with open(TASKS_FILE, "w", encoding="utf-8") as f:
        json.dump(tasks, f, ensure_ascii=False, indent=2)

def get_next_id(tasks):
    """为新任务生成下一个唯一ID。"""
    if not tasks:
        return 1
    return max(task["id"] for task in tasks) + 1

关键特性:

  • load_tasks优雅处理缺失或损坏的文件。
  • json.dump中的ensure_ascii=False确保Unicode支持。
  • indent=2保持JSON可读性。

用Tkinter构建GUI

我们创建一个TodoApp类来管理主窗口和小部件。界面包括:

Google AdInline article slot
  • 新任务输入框。
  • 显示所有任务的列表框。
  • 控制按钮:添加、标记完成、删除。
import tkinter as tk
from tkinter import messagebox

class TodoApp:
    def __init__(self, root):
        self.root = root
        self.root.title("任务管理器")
        self.root.geometry("500x400")
        self.root.resizable(False, False)
        self.tasks = load_tasks()
        self.create_widgets()
        self.refresh_task_list()

    def create_widgets(self):
        """设置所有UI元素。"""
        # 上方面板:输入框和添加按钮
        top_frame = tk.Frame(self.root)
        top_frame.pack(pady=10, padx=10, fill=tk.X)
        self.entry = tk.Entry(top_frame, font=("Arial", 12))
        self.entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
        self.entry.bind("<Return>", lambda event: self.add_task())
        self.add_button = tk.Button(top_frame, text="➕ 添加", command=self.add_task)
        self.add_button.pack(side=tk.RIGHT)
        # 任务列表带滚动条
        list_frame = tk.Frame(self.root)
        list_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        scrollbar = tk.Scrollbar(list_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.task_listbox = tk.Listbox(
            list_frame,
            font=("Arial", 11),
            yscrollcommand=scrollbar.set,
            selectmode=tk.SINGLE,
            height=15
        )
        self.task_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.task_listbox.yview)
        # 下方面板:操作按钮
        bottom_frame = tk.Frame(self.root)
        bottom_frame.pack(pady=10, padx=10, fill=tk.X)
        self.done_button = tk.Button(bottom_frame, text="✅ 完成", command=self.mark_done)
        self.done_button.pack(side=tk.LEFT, padx=5)
        self.delete_button = tk.Button(bottom_frame, text="🗑 删除", command=self.delete_task)
        self.delete_button.pack(side=tk.LEFT, padx=5)
        self.exit_button = tk.Button(bottom_frame, text="退出", command=self.root.quit)
        self.exit_button.pack(side=tk.RIGHT, padx=5)

    def refresh_task_list(self):
        """刷新任务列表显示。"""
        self.task_listbox.delete(0, tk.END)
        for task in self.tasks:
            status = "✓" if task["completed"] else "○"
            display_text = f"{status} {task['id']}. {task['text']}"
            self.task_listbox.insert(tk.END, display_text)

refresh_task_list处理读取操作,显示当前数据状态。勾选标记(✓/○)直观展示完成状态。

实现CRUD操作

接下来为类添加用户操作方法,每个对应一个CRUD操作。

创建:添加新任务

    def add_task(self):
        """添加新任务(创建)。"""
        text = self.entry.get().strip()
        if not text:
            messagebox.showwarning("警告", "请输入任务内容")
            return
        next_id = get_next_id(self.tasks)
        new_task = {
            "id": next_id,
            "text": text,
            "completed": False
        }
        self.tasks.append(new_task)
        save_tasks(self.tasks)
        self.entry.delete(0, tk.END)
        self.refresh_task_list()
        messagebox.showinfo("成功", f"任务已添加(ID: {next_id})")

更新:标记任务完成

    def mark_done(self):
        """标记选中任务为完成(更新)。"""
        selection = self.task_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请选择一个任务")
            return
        index = selection[0]
        task_id = self.tasks[index]["id"]
        for task in self.tasks:
            if task["id"] == task_id:
                if task["completed"]:
                    messagebox.showinfo("提示", "任务已完成")
                else:
                    task["completed"] = True
                    save_tasks(self.tasks)
                    self.refresh_task_list()
                    messagebox.showinfo("成功", f"任务#{task_id}已标记完成")
                return

删除:移除任务

    def delete_task(self):
        """删除选中任务(删除)。"""
        selection = self.task_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请选择一个任务")
            return
        index = selection[0]
        task_id = self.tasks[index]["id"]
        task_text = self.tasks[index]["text"]
        if messagebox.askyesno("确认", f"删除任务#{task_id}「{task_text}」?"):
            del self.tasks[index]
            save_tasks(self.tasks)
            self.refresh_task_list()
            messagebox.showinfo("成功", f"任务#{task_id}已删除")

每个方法都验证输入、更新内存数据、保存文件并刷新UI。消息框提供清晰的用户反馈。

Google AdInline article slot

组装并运行应用

将所有内容整合到一个文件中,添加主入口。

if __name__ == "__main__":
    root = tk.Tk()
    app = TodoApp(root)
    root.mainloop()

python app.py运行。测试所有CRUD操作——应用会在会话间保存数据到tasks.json

关键要点

  • CRUD基础:创建、读取、更新、删除驱动大多数数据应用。
  • JSON存储:小项目理想选择,无需数据库。
  • Tkinter GUI:零依赖、跨平台的快速桌面UI。
  • 干净代码结构:数据模型(JSON)、视图(Tkinter)和逻辑(TodoApp)分离,便于维护。
  • 错误处理:验证输入,捕获如坏JSON等问题。

进阶扩展

扩展你的任务管理器:

  • 任务分类 支持筛选。
  • 截止日期datetime和颜色标记。
  • 导出 到CSV或Excel。
  • 数据库集成 (SQLite、PostgreSQL)。
  • Web版本 用Flask或Django。

这个项目展示了核心编程概念如何应用于实际开发,为进阶主题打下坚实基础。

— Editorial Team

Advertisement 728x90

继续阅读