如何让Python记住设置?

rec*_*gle 1 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()
Run Code Online (Sandbox Code Playgroud)

编辑:

我尝试了以下代码

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()
Run Code Online (Sandbox Code Playgroud)

但是得到以下错误

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
Run Code Online (Sandbox Code Playgroud)

Dav*_*d Z 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()))
Run Code Online (Sandbox Code Playgroud)

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