我刚刚开始使用 Tkinter 进行编程类(class),但在使用文件对话框处理程序时遇到了一些问题。 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")
最佳答案
我很清楚,当您将文件句柄 self.lastopen
和 self.lastsave
设置为与 False
相同的值时调用filesave
。您是否检查过它们在 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
关于python - tkFileDialog 文件保存方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6798312/