Skip to main content
 首页 » 编程设计

python之使用 pickle 加载类的状态

2025年05月04日23cyq1162

我想用 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(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() 

所以这个应用程序的目标是一旦我按下加号按钮,屏幕上的数字就会增加。如果我保存它,关闭窗口,重新打开它,然后点击加载按钮,我将看到上次我增加到的数字。我是 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 

with 是什么意思?

请您参考如下方法:

你的问题可以简化为一个根本不使用 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 

您正在 pickle __getstate__ 实例方法,而不是 start 类的完整状态。 Python 允许您这样做,假设您还实现了一个知道如何根据该信息重建对象的 __setstate__ 方法。来自docs :

Upon unpickling, if the class defines __setstate__(), it is called with the unpickled state. In that case, there is no requirement for the state object to be a dictionary. Otherwise, the pickled state must be a dictionary and its items are assigned to the new instance’s dictionary.

当你 unpickle 时,pickle 会创建一个新的 state 实例,但由于该类没有 __setstate__ 方法,pickle 会尝试恢复对象的 __dict__。这失败了,因为 unpickled 对象是实例方法,而不是 dict。这表明您的方法存在更大的问题。

pickle 重新创建整个对象,它不会恢复到现有对象中。在您的情况下,如果您 pickle 了整个 start 对象,除了您自己创建的对象之外,它还会恢复第二个 start 对象。您可以将该对象的 __dict__ 分配给您的 __dict__,但这是一个非常冒险的提议。您将失去 Frame 对象的整个状态,以支持您 pickle 的对象中发生的情况。因为 tkinter 是一个 C 扩展模块,所以无论如何都不可能 pickle 整个对象。

相反,您应该将要保存和恢复的数据与碰巧用于与用户交互的 tkinter 对象分开。这是一个常见的编程规则:将数据与表示分开。在这里,我有一个保存数据的类,我可以将它与 tkinter 类分开保存和恢复。

import tkinter as tk 
import pickle 
 
class State: 
    def __init__(self): 
        self.val = 0 
 
 
class start(tk.Frame): 
    def __init__(self,*args,**kwargs): 
        tk.Frame.__init__(self,*args,**kwargs) 
        frame = tk.Frame(self,width=600,height=600) 
        self.state = State() 
        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.state = pickle.load(open( "testtesttest.p", "rb" )) 
        self.valLabel.config(text="%d"%(self.state.val)) 
    def plus(self): 
        self.state.val += 1  
        self.valLabel.config(text="%d"%(self.state.val)) 
    def save(self): 
        pickle.dump(self.state, open( "testtesttest.p", "wb" ), 4) 
 
if __name__=='__main__': 
   root = tk.Tk() 
 
   start(root).pack() 
   root.mainloop()