【问题标题】:TypeError: can't pickle _tkinter.tkapp objects while using dill libraryTypeError: can't pickle _tkinter.tkapp objects while using dill library
【发布时间】:2020-08-29 10:23:32
【问题描述】:

所以,我有这样的课:

class Category:
def __init__(self,name):
    self.bt = Button(t, text = name, command = lambda : opencategory(name))
    self.packing()
def packing(self):
    self.bt.pack(fill = X)
def pack_forg(self):
    self.bt.pack_forget()

然后我创建类别对象列表,例如:

list_cat = [Category("a"), Category("b"), Category("c")]

我使用 dill 模块将此列表保存到文件中:

   if list_cat != []:
        with open("file.pkl","wb") as f2:
            dill.dump(list_cat, f2)

但是当我运行它时,它返回TypeError: can't pickle _tkinter.tkapp 我愿意接受任何类型的解决方案,使用 JSON、pickle、dill 或其他任何东西。

这是一个完整的工作代码:

from tkinter import *
import os.path
from os import path
import dill

t = Tk()
t.title("test7")
t.geometry("100x300")
a = 1
list_cat = []

if path.exists("test777.pkl"):
    with open("test777.pkl","rb") as filee:
        list_cat = dill.load(filee)    

def opencategory(sampletext):
    print(sampletext)

class Category:  
    def __init__(self,sampletext):
        self.bt = Button(t, text = sampletext, command = lambda : opencategory(sampletext))
        self.packing()
    def packing(self):
        self.bt.pack(fill = X)
    def pack_forg(self):
        self.bt.pack_forget()


def save_c():
    if list_cat != []:
        with open("test777.pkl","wb") as file:
            dill.dump(list_cat, file)
def add_c():
    global a 
    list_cat.append(Category(a))
    a += 1


save = Button(t, text = "save", command = save_c)
save.pack(fill = X)
add = Button(t, text = "add", command = add_c)
add.pack(fill = X)


for i in list_cat:
    i.packing()

【问题讨论】:

  • 不是还有什么东西也叫li​​st_cat或f2吗?另请发布完整的工作代码!

标签: python tkinter compiler-errors pickle dill


【解决方案1】:

您正在尝试腌制一个对象列表。这些对象中的每一个都包含一个小部件。你不能腌制小部件。根本做不到。

【讨论】:

    【解决方案2】:

    我是dill 作者。我同意@Bryan_Oakley。但更清楚地说,_tkinter 不是 python(我相信它是 C++)。问题是任何 python 序列化程序都无法腌制非 python 对象,除非位于它上面的 python 类提供序列化指令(就像numpy 数组一样)。 Tkinter 没有。

    您可以在dill(dill.settings)中尝试不同的序列化变体,但很可能会失败。

    您可能会构建一个派生类的小部件,您可以在其中添加序列化指令,通知序列化程序如何存储小部件的状态。这应该可行——而且本质上,它可以让任何类对象成为可序列化的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 2018-08-31
      相关资源
      最近更新 更多