tkFileDialog 文件保存方法不起作用
我刚开始学习使用Tkinter来上编程课,但在使用文件对话框时遇到了一些问题。fileopen和filesaveas这两个方法都能正常工作,但filesave方法却不行。
这个功能要求filesave方法应该保存到最后一次保存的文件;如果没有保存过的文件,就保存到最后一次打开的文件;如果这两者都没有,就保存为默认的名字quiz_spec.py。奇怪的是,前两个写入调用在执行时似乎没有保存文件(而且也没有产生任何错误)。
如果有人能告诉我为什么filesaveas和filesave中的保存调用表现得不一样,并且给我一个好的tkFileDialog保存功能的例子,我会非常感激。
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")
2 个回答
2
我搞明白了,原来是我没有关闭文件。真是傻啊。
2
我觉得很明显,你的文件句柄 self.lastopen
和 self.lastsave
在你调用 filesave
的时候被设置成了某种相当于 False
的值。你有没有检查过它们在你的 fileopen
和 filesave
函数结束后是否还保持原来的状态?这样调试起来很简单,可以试试:
my_man = FileMan()
my_man.fileopen()
my_man.filesave()
print my_man.lastopen
print my_man.lastsave
如果这样不行,可以更新你的问题,告诉我们这个方法的结果,我们再继续帮你解决。另外,你还应该检查一下:
print my_man.lastopen == False and my_man.lastsave == False