Python 使用pickle加载类的状态
我想用pickle把脚弄湿,所以我写了一个小示例代码,如下所示:Python 使用pickle加载类的状态,python,tkinter,pickle,Python,Tkinter,Pickle,我想用pickle把脚弄湿,所以我写了一个小示例代码,如下所示: class start(tk.Frame): def __init__(self,*args,**kwargs): tk.Frame.__init__(self,*args,**kwargs) frame = tk.Frame(self,width=600,height=600) self.val = 0 self.plusButton = tk.Button
class start(tk.Frame):
def __init__(self,*args,**kwargs):
tk.Frame.__init__(self,*args,**kwargs)
frame = tk.Frame(self,width=600,height=600)
self.val = 0
self.plusButton = tk.Button(self,text="plus",command=self.plus)
self.plusButton.pack()
self.valLabel = tk.Label(self)
self.valLabel.pack()
self.saveButton = tk.Button(self,text="save",command=self.save)
self.saveButton.pack()
self.loadButton = tk.Button(self,text="load",command=self.load)
self.loadButton.pack()
def load(self):
self.__dict__ = pickle.load(open( "testtesttest.p", "rb" ))
def plus(self):
self.val += 1
self.valLabel.config(text="%d"%(self.val))
def save(self):
pickle.dump(self.__getstate__, open( "testtesttest.p", "wb" ))
def __getstate__(self):
return self.__getstate__
if __name__=='__main__':
root = tk.Tk()
start(root).pack()
root.mainloop()
因此,这个应用程序的目标是,一旦我按下plusbutton,屏幕上的数字就会越来越多。如果我保存它,关闭窗口,重新打开它,然后点击加载按钮,我将看到上一次我增加到的数字。我对pickle非常陌生,当前的代码告诉我:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__return self.func(*args)
File "/Users/caoanjie/pickleDemotry.py", line 18, in load
self.__dict__ = pickle.load(open( "testtesttest.p", "rb" ))pickle.
UnpicklingError: state is not a dictionary
我不知道这里有什么问题。此外,我在网上看到了很多教程或示例代码,它们的功能如下:
with open('save_game.dat', 'wb') as f:
player= pickle.load
和
是什么意思?您的问题可以简化为一个不使用tkinter的小班:
>>> class Foo:
... def __getstate__(self):
... print('getstate')
... return self.__getstate__
...
>>> obj = pickle.loads(pickle.dumps(Foo().__getstate__))
getstate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_pickle.UnpicklingError: state is not a dictionary
您的问题可以简化为一个完全不使用tkinter的小班:
>>> class Foo:
... def __getstate__(self):
... print('getstate')
... return self.__getstate__
...
>>> obj = pickle.loads(pickle.dumps(Foo().__getstate__))
getstate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_pickle.UnpicklingError: state is not a dictionary
-与文件对象一起使用时,它确保即使引发异常也关闭文件。网上有很多参考资料,这个可能会有帮助。这里是一个SO问答-通常,您应该在问题中始终发布完整的回溯。
def\uu getstate\uuuuuuuuuu(self):
看起来有问题-如果您手动调用它,它会返回什么?虽然它可能无法直接解决您的问题,这样的问答可能值得一读-。您可能会注意到,在这里和其他地方阅读Python代码时,类名总是以大写字母开头。这是Python风格指南的一个方面,似乎得到了普遍的实现与文件对象一起使用时,它确保即使引发异常也关闭文件。网上有很多参考资料,这个可能会有帮助。这里是一个SO问答-通常,您应该在问题中始终发布完整的回溯。def\uu getstate\uuuuuuuuuu(self):
看起来有问题-如果您手动调用它,它会返回什么?虽然它可能无法直接解决您的问题,这样的问答可能值得一读-。您可能会注意到,在这里和其他地方阅读Python代码时,类名总是以大写字母开头。这是Python风格指南的一个方面,它似乎得到了普遍的实现。@angieShroom-很高兴我能提供帮助。如果这对你有效,接受它作为答案,让其他人知道。@angieShroom-很高兴我能帮助你。如果这对你有效,接受它作为答案,让别人知道。