【发布时间】:2016-11-23 15:45:28
【问题描述】:
我想用泡菜弄湿我的脚,所以我写了一个像这样的小示例代码:
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()
所以这个应用程序的目标是一旦我点击加号按钮,屏幕上就会出现越来越多的数字。如果我保存它,关闭窗口,重新打开它,然后点击加载按钮,我会看到我最后一次增加到的数字。我对泡菜很陌生,当前的代码还给了我:
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
with 是什么意思?
【问题讨论】:
-
within the docs - 当与文件对象一起使用时,它确保即使引发异常也关闭文件。网上有很多参考资料,这个可能会有所帮助 - effbot.org/zone/python-with-statement.htm。这是一个 SO Q&A - stackoverflow.com/q/1369526/2823755 -
通常情况下,您应该始终在问题中发布完整的 Traceback。
-
def __getstate__(self):看起来有问题 - 如果您手动调用它会返回什么? -
虽然它可能无法直接解决您的问题,但此 SO Q&A 可能值得一读 - stackoverflow.com/q/4529815/2823755。
-
在 SO 和其他地方阅读 Python 代码时,您可能会注意到类名总是以大写字母开头。这是 Python 风格指南python.org/dev/peps/pep-0008 的一个方面,似乎已被普遍实现。