2010-06-27 129 views
0

我写了下面的美丽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() 

编辑:

我尝试下面的代码

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 

回答

4

的刻度值写入一个文件,并在阅读在启动。这里有一个办法做到这一点(大约),

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

显然,你可以使它更强大的/复杂的/如果复杂,比如,要保存和恢复附加值。

+0

我想这样,但出现以下错误: 回溯(最近通话最后一个): 文件“”,线路244,在run_nodebug 文件“C:\ Python26 \ pickleexample.py”,行30,在 与开放(CONFIG_FILE,'w')作为f: IOError:[Errno 2]没有这样的文件或目录:'库\\ Documents \\ T.txt' 如何正确设置文件目录? – rectangletangle 2010-06-27 23:50:22

+0

这可能意味着您尝试创建的文件的父目录之一不存在。确保你在'CONFIG_FILE'中指定的文件的父目录存在。例如,如果你设置了'CONFIG_FILE ='Libraries \ Documents \ T.txt'',确保目录'Libraries \ Documents'(相对于你运行Python脚本的目录)存在。尽管我实际上推荐使用绝对路径(一个以驱动器号开头的路径),例如'CONFIG_FILE ='C:\ SomeFolder \ Libraries \ Documents \ T.txt''。这种方式不那么令人困惑。 – 2010-06-28 00:14:43

1

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

是否有任何“save.txt的”?

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

如果参数已更新,则将其重写到文件中。

我不是专家的Python,但应该有一些好的库mainloop之前只是为了读取和写入文件:)

3

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腌制配置可以安全地重新加载)。

0

在解释一个简单的使用

help(cPickle.dump) 

会立即显示,你应该尝试通过交换f和存储在呼叫对象改变Alex的代码:

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

对于客体的持久性有在Python中是一个很好的模块:搁置。

例如(这两个脚本是在同一目录中)

脚本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。一个更完整的例子我的帖子由GDDC答案: Importing python variables of a program after its execution