I'm trying to get my feet wet with pickle, so I write a little sample code like this:
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()
So the goal of this app is once I hit the plusbutton, there will be an increasing number on the screen. And if I save it, close the window, reopen it, and hit the load button, I will see the last time the number I increased to. I'm very new to pickle, and the current code gives this back to me:
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
I wonder what the problem is here. Also, I see a lot of tutorials or sample code online that does things like:
with open('save_game.dat', 'wb') as f:
player= pickle.load
What does with
mean?