我用 tkinter 编写了一个使用类作为结构的应用程序。目前我尝试实现一个“保存”功能,以便可以关闭应用程序,如果它重新启动,则决定是从头开始还是使用已经存在的 aka。腌制数据。
我读到了 pickle-module 及其无法保存类变量的弱点,所以我决定改用 dill-module。
我的问题: dill 保存了我的类变量的起始值,但是如果我让用户更改类变量(通过调用 classmethods),则不会保存更改。有什么办法可以用泡菜或莳萝模块做到这一点?
我创建了一个产生错误的最小示例。您可以看到,即使在调用更改变量的实例方法之后,实例变量的更改也会被保存。不幸的是,它不适用于类变量,它是相应的类方法:
import dill as pickle
from tkinter import *
root = Tk()
# creating class
class Roomie:
# class variable: total number of expenses
num_exp = 0
# init method: every roomie has a name, info for each expense, etc...
def __init__(self,fname,exp=0.00):
self.fname = fname
self.exp = exp
def raiseExp(self):
self.exp += 1
# class method: every time someone spend smth value of class variable num_exp increases by one
@classmethod
def updateExpNum(cls):
cls.num_exp += 1
# saving instance of class in list object
roomie_0 = Roomie("Cthulhu")
roomie_list = [roomie_0]
def pickleRoomies():
file_Name = "debts.pkl"
# open file for writing
fileObject = open(file_Name,'wb')
# write roomie_list to file
pickle.dump(roomie_list,fileObject)
# here we close the fileObject
fileObject.close()
# load all instances and class variables
def loadPickle():
global roomie_list
filepath = "debts.pkl"
file = open(filepath, "rb" )
roomie_list = pickle.load(file)
# create buttons and bind instance and class methods to them
button_0 = Button(root,text="update number of expenses",command=lambda: Roomie.updateExpNum())
button_1 = Button(root,text="raise expense",command=lambda: roomie_list[0].raiseExp())
button_2 = Button(root,text="save changes",command=lambda: pickleRoomies())
button_3 = Button(root,text="load changes",command=lambda: loadPickle())
button_0.pack()
button_1.pack()
button_2.pack()
button_3.pack()
# run GUI
root.mainloop()
# check program
# print instance variable
print("total expenses:",roomie_list[0].exp)
# print class variable
print("number of expenses:", Roomie.num_exp)
# print instance variable
print("name:", roomie_list[0].fname)