Skip to content Skip to sidebar Skip to footer

Pickle Will Not Work With Tkinter

I'm making a little game with Tkinter, and it has a save function using pickle. However, when I try to save, it throws up the following message; Exception in Tkinter callback Trace

Solution 1:

The short answer is, you can't pickle anything tkinter related. The reason is that tkinter applications use an embedded Tcl interpreter which maintains the state of the GUI in memory, and Tcl doesn't know anything about the python pickle format (and likewise, pickle knows nothing about the tcl interpreter). There's simply no way to save and restore the data managed by the Tcl interpreter.

You will have to convert the information you want to save into some type of data structure, and then save and load this data structure.

For example

defsave(self):
    data = {"name": self.name,
            "nodes": self.nodes,
            ...
           }
    withopen('data.json', 'w') as f:
        json.dump(data, f)

defload(self):
    withopen('data.json') as f:
        data = json.load(f)
    self.name = data["name"]
    self.nodes = data["nodes"]
    ...

If any of the values you want to store contain references to tkinter objects (eg: widgets, list of canvas item ids, etc.), you'll have to convert them to something else, and restore them at startup.

Solution 2:

In addition to what Brian Oakley suggested, it is also possible to save data as dill export:

defsave(self):
    data = {"name": self.name,
            "nodes": self.nodes,
            ...
           }
    withopen('data.pkl', 'wb') as f:
        dill.dump(data, f)

defload(self):
    withopen('data.pkl', 'rb') as f:
        data = dill.load(f)
    self.name = data["name"]
    self.nodes = data["nodes"]
    ...

Note that here it is necessary to specify binary mode at opening the file.

Post a Comment for "Pickle Will Not Work With Tkinter"