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?
JavaScript
x
11
11
1
import Tkinter
2
3
root = Tkinter.Tk()
4
5
root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1)
6
root.sclX.pack(ipadx=75)
7
8
root.resizable(False,False)
9
root.title('Scale')
10
root.mainloop()
11
Edit:
I tried the following code
JavaScript
1
20
20
1
import Tkinter
2
import cPickle
3
4
5
root = Tkinter.Tk()
6
7
root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1)
8
root.sclX.pack(ipadx=75)
9
10
11
12
root.resizable(False,False)
13
root.title('Scale')
14
15
16
with open('myconfig.pk', 'wb') as f:
17
cPickle.dump(f, root.config(), -1)
18
cPickle.dump(f, root.sclX.config(), -1)
19
root.mainloop()
20
But get the following error
JavaScript
1
6
1
Traceback (most recent call last):
2
File "<string>", line 244, in run_nodebug
3
File "C:Python26pickleexample.py", line 17, in <module>
4
cPickle.dump(f, root.config(), -1)
5
TypeError: argument must have 'write' attribute
6
Advertisement
Answer
Write the scale value to a file and read it in on startup. Here’s one way to do it (roughly),
JavaScript
1
17
17
1
CONFIG_FILE = '/path/to/config/file'
2
3
root.sclX =
4
5
try:
6
with open(CONFIG_FILE, 'r') as f:
7
root.sclX.set(int(f.read()))
8
except IOError: # this is what happens if the file doesn't exist
9
pass
10
11
12
root.mainloop()
13
14
# this needs to run when your program exits
15
with open(CONFIG_FILE, 'w') as f:
16
f.write(str(root.sclX.get()))
17
Obviously you could make it more robust/intricate/complicated if, for instance, you want to save and restore additional values.