需求

我在程序主页面勾选了一些checkbutton的选项,并且希望下次打开程序,这些选项能保持我上次勾选的状态

Python Ttk 之 让Checkbutton记住你的选择_数据

比如我勾选的选项,退出程序后进来仍然还在,没有被重置,这就可以了。

实现

布局什么就不实现了,直接贴代码:

import json
import tkinter as tk

def checkbutton1_clicked():
    if var1.get() == 1:
        print("Checkbutton被选中")
        setLocalJsonCfg('checkbutton1_check', 1)
    else:
        print("Checkbutton未被选中")
        setLocalJsonCfg('checkbutton1_check', 0)

def checkbutton2_clicked():
    if var2.get() == 1:
        setLocalJsonCfg('checkbutton2_check', 1)
        print("Checkbutton2被选中")
    else:
        setLocalJsonCfg('checkbutton2_check', 0)
        print("Checkbutton2未被选中")

def getLocalJsonCfg(jsonKey):
    josnFile = open('checkbutton.json', 'rb')
    cfg = json.load(josnFile)
    return cfg[jsonKey]

def setLocalJsonCfg(jsonKey, jsonValue):
    # 读取 JSON 文件内容
    with open('checkbutton.json', 'r') as file:
        data = json.load(file)
    # 修改 JSON 数据
    data[jsonKey] = jsonValue
    # 写入修改后的 JSON 数据到文件
    with open('checkbutton.json', 'w') as file:
        json.dump(data, file, indent=4)

root = tk.Tk()

var1 = tk.IntVar(value=getLocalJsonCfg('checkbutton1_check'))
var2 = tk.IntVar(value=getLocalJsonCfg('checkbutton2_check'))
checkbutton1 = tk.Checkbutton(root, text="选中我", variable=var1, command=checkbutton1_clicked)
checkbutton1.pack()
checkbutton2 = tk.Checkbutton(root, text="选中我", variable=var2, command=checkbutton2_clicked)
checkbutton2.pack()

checkbutton1_clicked()
checkbutton2_clicked()
root.mainloop()

实现方式

其实就是用json保存勾选的状态,每次对json文件进行读取勾选配置,让修改了勾选状态,就去更新json文件就好啦


Python Ttk 之 让Checkbutton记住你的选择_JSON_02