Skip to content
Advertisement

How do I make Python remember settings?

I wrote the beautiful python example code below. Now how do I make it so when I exit then restart the program it remembers the last position of the scale?

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

Edit:

I tried the following code

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

But get the following error

Traceback (most recent call last):
  File "<string>", line 244, in run_nodebug
  File "C:Python26pickleexample.py", line 17, in <module>
    cPickle.dump(f, root.config(), -1)
TypeError: argument must have 'write' attribute

Advertisement

Answer

Write the scale value to a file and read it in on startup. Here’s one way to do it (roughly),

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

Obviously you could make it more robust/intricate/complicated if, for instance, you want to save and restore additional values.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement