如何让Python记住设置?

时间:2010-06-27 19:52:03

标签: python memory tkinter python-2.x

我在下面编写了漂亮的python示例代码。现在,当我退出然后重新启动程序时,我如何才能这样做,它会记住刻度的最后位置?

import Tkinter

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')
root.mainloop()

修改

我尝试了以下代码

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

5 个答案:

答案 0 :(得分:5)

将缩放值写入文件并在启动时读取。这是一种方法(粗略地),

CONFIG_FILE = '/path/to/config/file'

root.sclX = ...

try:
    with open(CONFIG_FILE, 'r') as f:
        root.sclX.set(int(f.read()))
except IOError:    # this is what happens if the file doesn't exist
    pass

...
root.mainloop()

# this needs to run when your program exits
with open(CONFIG_FILE, 'w') as f:
    f.write(str(root.sclX.get()))

显然,如果你想保存和恢复其他值,你可以使它更健壮/更复杂/更复杂。

答案 1 :(得分:3)

mainloop

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

并且,在后续运行时(当.pk文件已存在时),相应的cPickle.load调用将其恢复并使用...config(**k)进行设置(还需要一些技巧来确认不幸的是,cPickle腌制配置可以安全地重新加载。

答案 2 :(得分:1)

您可以告诉程序使用参数编写一个名为“save.txt”的文件,然后在进一步的执行中加载它:

有没有“save.txt”?

否:使用参数编写新的保存文件。 是:读取参数并将其传递给变量。

如果参数已更新,请在文件中重写。

我不是Python的专家,但是应该有一些很好的库来读写文件:)

答案 3 :(得分:0)

简单使用

help(cPickle.dump)
解释器中的

将立即显示您应该尝试通过交换f和存储在调用中的对象来更改Alex的代码:

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

答案 4 :(得分:0)

对于objet持久性,Python中有一个很好的模块:搁置。

e.g。 (这两个脚本位于同一目录中)

脚本1

import shelve

settings = shelve.open('mySettings')
settings['vroot_directory'] = commands.getoutput("pwd")

脚本2

import shelve 

settings = shelve.open('mySettings')
root_directory_script1 = settings['vroot_directory'])   

RGDS,

PS。有关更完整的示例,请参阅g.d.d.c的帖子:  Importing python variables of a program after its execution

相关问题