【发布时间】: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()
【问题讨论】:
-
不是还有什么东西也叫list_cat或f2吗?另请发布完整的工作代码!
标签: python tkinter compiler-errors pickle dill