Python 2.6中cPickle的帮助

4 投票
2 回答
1765 浏览
提问于 2025-04-16 00:45

我在Python中尝试了以下代码。这是我第一次尝试使用“序列化”。

import Tkinter
import cPickle


root = Tkinter.Tk()

root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1)
root.sclX.pack(ipadx=75)



root.resizable(False,False)
root.title('Scale')


with open('myconfig.pk', 'wb') as f:
    cPickle.dump(f, root.config(), -1)
    cPickle.dump(f, root.sclX.config(), -1)
root.mainloop()

但是我遇到了以下错误:

Traceback (most recent call last):
  File "<string>", line 244, in run_nodebug
  File "C:\Python26\pickleexample.py", line 17, in <module>
    cPickle.dump(f, root.config(), -1)
TypeError: argument must have 'write' attribute

我哪里做错了?

编辑:

我尝试了以下代码,现在它可以正常工作了!那么我该如何让程序重新启动时,滑块的位置保持在上次关闭程序时的状态呢?

import Tkinter
import cPickle


root = Tkinter.Tk()

root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1)
root.sclX.pack(ipadx=75)



root.resizable(False,False)
root.title('Scale')


with open('myconfig.pk', 'wb') as f:
    cPickle.dump(root.config(), f, -1);
    cPickle.dump(root.sclX.config(), f, -1);
root.mainloop()

2 个回答

1

我觉得你把参数的顺序搞错了。可以查看文档,在这里。试试下面的代码:

cPickle.dump(root.config(), f, -1);
cPickle.dump(root.sclX.config(), f, -1);
2

试着换一下参数的顺序:

cPickle.dump(root.config(), f, -1)
cPickle.dump(root.sclX.config(), f, -1)

根据文档的说明,文件应该是第二个参数,而要进行序列化的对象应该是第一个。

撰写回答