我在下面编写了漂亮的 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
请您参考如下方法:
将比例值写入文件并在启动时读入。这是一种方法(大致),
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()))
显然,例如,如果您想保存和恢复额外的值,您可以让它更健壮/更复杂/更复杂。
