Python Tkinter待办应用删除JSON数据失败问题求助
解决Tkinter待办应用删除任务时无法修改JSON文件的问题
要实现输入任务ID后同步删除ids.json中的ID和cards.json中的对应任务,核心是正确完成「读取文件→修改数据→写入文件」的完整流程,以下是具体实现方案:
核心实现代码
首先编写通用的删除函数,处理两个JSON文件的修改:
import json def delete_task(task_id_input): # 统一处理ID类型(根据你的JSON文件实际类型调整,比如数字转字符串或反之) try: task_id = int(task_id_input) task_id_str = str(task_id) except ValueError: print("请输入有效的数字ID") return # 处理ids.json:移除目标ID try: # 读取现有ID列表 with open("ids.json", "r", encoding="utf-8") as f: ids_list = json.load(f) if task_id in ids_list: ids_list.remove(task_id) # 写入修改后的列表 with open("ids.json", "w", encoding="utf-8") as f: json.dump(ids_list, f, ensure_ascii=False, indent=4) else: print(f"ID {task_id} 不存在于ids.json中") except FileNotFoundError: print("未找到ids.json文件") except json.JSONDecodeError: print("ids.json文件格式错误,请检查") # 处理cards.json:删除对应ID的任务 try: # 读取现有任务字典 with open("cards.json", "r", encoding="utf-8") as f: cards_dict = json.load(f) if task_id_str in cards_dict: del cards_dict[task_id_str] # 写入修改后的字典 with open("cards.json", "w", encoding="utf-8") as f: json.dump(cards_dict, f, ensure_ascii=False, indent=4) else: print(f"ID {task_id} 对应的任务不存在于cards.json中") except FileNotFoundError: print("未找到cards.json文件") except json.JSONDecodeError: print("cards.json文件格式错误,请检查")
在Tkinter中调用删除函数
假设你有一个输入ID的输入框和删除按钮,绑定点击事件即可:
import tkinter as tk root = tk.Tk() root.title("待办任务删除") # 创建ID输入框 id_entry = tk.Entry(root, width=20) id_entry.pack(pady=10) id_entry.insert(0, "请输入任务ID") # 创建删除按钮并绑定函数 def handle_delete(): input_id = id_entry.get().strip() if not input_id: print("请输入任务ID") return delete_task(input_id) delete_btn = tk.Button(root, text="删除任务", command=handle_delete) delete_btn.pack(pady=5) root.mainloop()
常见问题排查
- 类型不匹配:如果你的
ids.json中存储的是数字,而输入的是字符串,会导致remove失败;cards.json的键默认是字符串,所以要把数字ID转成字符串再查找。 - 忘记写入文件:修改完列表/字典后,必须重新用
json.dump写入文件,否则修改不会生效。 - 文件打开模式错误:不要用
r+模式直接写入,建议先读取文件内容到内存,修改后用w模式覆盖写入,避免残留旧内容。 - 文件不存在或格式错误:添加异常处理可以快速定位这类问题,避免程序崩溃。
内容的提问来源于stack exchange,提问作者Luis Gomes
相关产品推荐
相关产品推荐

