I have just started using Tkinter for a programming class and am having a bit of trouble using file dialog handlers. The fileopen and filesaveas methods work correctly, but the filesave method is not.
The specification requires that the filesave method should save to the last saved file; if no file has been saved, then save to the last opened file; else save to the default name quiz_spec.py. For some reason, the first two write calls don’t seem to be saving save the file when they are reached (and aren’t generating any errors either.)
It would be appreciated if someone could please tell me why the same save calls in filesaveas and filesave are functioning differently and also point me to a good example of a tkFileDialog save function.
class FileMan():
def __init__(self):
self.lastsave = None
self.lastopen = None
def fileopen(self):
handle = askopenfile(mode = 'r')
print "name of file you picked = "+str(handle.name)
self.lastopen = handle
print "first line of data from file: "+handle.readline()
def filesave(self):
if (self.lastsave):
self.lastsave.write("Save: Some data to save into the file\n")
elif (self.lastopen):
self.lastopen.write("Save: Some data to save into the file\n")
else:
handle = open('quiz_spec.py', 'w')
handle.write("Save: This is the new content of test.txt :-)")
def filesaveas(self):
handle = asksaveasfile(mode = 'w', defaultextension = '.py')
print "name of file you picked = "+str(handle.name)
self.lastsave = handle
handle.write("SaveAs: Some data to save into the file\n")
Pretty clear to me that your file handles
self.lastopenandself.lastsaveare set to some equivalent ofFalseby the time you callfilesave. Did you check that they persist after yourfileopenandfilesavefunctions exit? Pretty simple to debug this way, try:If this doesn’t work, try updating your question with the results of this and we’ll take it from there. Also, you should check if: