如何使Python记住设置?

2024-05-16 11:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我写的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()

编辑:

我尝试了下面的代码

^{pr2}$

但是得到以下错误

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

Tags: to代码infromimport程序falsetkinter
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可以安全地重新加载pickled配置)。在

将刻度值写入文件,并在启动时读取。这里有一种方法(粗略地说)

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()))

显然,如果您希望保存和恢复其他值,那么您可以使它更加健壮/复杂/复杂。在

你可以告诉程序写一个文件,例如保存.txt“使用参数,然后在以后的执行中加载它:

有没有“保存.txt"? 在

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

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

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

相关问题 更多 >