You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter中永久保存用户修改的嵌入式字典?

实现字典数据的永久保存方案

一、使用JSON模块实现

JSON是轻量级文本格式,适合存储结构化数据,优点是可读性强、跨平台兼容,完全满足你的需求。

实现逻辑

  1. 程序启动时优先从JSON文件加载数据,文件不存在则使用初始字典
  2. 用户修改数据后,立即将更新后的字典写入JSON文件完成持久化

修改后的代码示例

import json
import tkinter as tk
from tkinter import Button

# 定义数据存储文件路径
DATA_FILE = "line_7_data.json"

# 加载数据函数
def load_data7():
    try:
        with open(DATA_FILE, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        # 文件不存在时返回初始字典
        return {
            'Conveyor 701': {'Serial #': "212.3", 'Asset #': '60528', 'Machine Voltage':'none', 'Breaker #': 'none', 
                             'Utility Air Pressure':'none', 'IP Address': 'none', 'HMI Model':'none', 'HMI Program': 'none', 
                             'HMI Battery':'none', 'PLC Model': 'none', 'PLC Program':'none', 'PLC Battery': 'none', 
                             'Additional Notes' : 'None'}
        }

# 初始化字典
line_7_lst = load_data7()

def save_input7():
    # 注意:machine_choice7、attributeinput7、user_input7需提前定义
    line_7_lst[machine_choice7][attributeinput7] = user_input7
    # 写入JSON文件完成保存
    with open(DATA_FILE, 'w') as f:
        json.dump(line_7_lst, f, indent=4)

# Tkinter界面代码
line_7 = tk.Tk()
buttonadd7 = Button(line_7, text="Add", command=save_input7)
buttonadd7.pack()
buttonadd7.place(x=1085, y=189)

line_7.mainloop()

二、使用shelf模块实现

shelf是Python标准库的持久化字典工具,操作方式和原生字典几乎一致,数据以二进制格式存储,适合需要直接操作类字典对象的场景。

实现逻辑

  1. 打开shelf文件后直接操作类字典对象
  2. 开启writeback=True后,修改数据会自动同步到文件,无需手动序列化

修改后的代码示例

import shelve
import tkinter as tk
from tkinter import Button

# 定义shelf存储文件路径
SHELF_FILE = "line_7_data.db"

def save_input7():
    with shelve.open(SHELF_FILE, writeback=True) as db:
        # 初始化数据(仅第一次运行时执行)
        if 'line_7_lst' not in db:
            db['line_7_lst'] = {
                'Conveyor 701': {'Serial #': "212.3", 'Asset #': '60528', 'Machine Voltage':'none', 'Breaker #': 'none', 
                                 'Utility Air Pressure':'none', 'IP Address': 'none', 'HMI Model':'none', 'HMI Program': 'none', 
                                 'HMI Battery':'none', 'PLC Model': 'none', 'PLC Program':'none', 'PLC Battery': 'none', 
                                 'Additional Notes' : 'None'}
            }
        # 修改数据
        db['line_7_lst'][machine_choice7][attributeinput7] = user_input7

# 程序启动时加载数据
def load_data7():
    with shelve.open(SHELF_FILE) as db:
        return db.get('line_7_lst', {})

line_7_lst = load_data7()

# Tkinter界面代码
line_7 = tk.Tk()
buttonadd7 = Button(line_7, text="Add", command=save_input7)
buttonadd7.pack()
buttonadd7.place(x=1085, y=189)

line_7.mainloop()

两种方案对比

  • JSON:文本格式可直接打开编辑,跨语言兼容性好,适合简单结构化数据
  • shelf:操作更接近原生字典,支持更多Python对象类型,但数据不可直接查看,仅适用于Python环境

内容的提问来源于stack exchange,提问作者bradenzingler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:45:31