【问题标题】:tkFileDialog filesave method not workingtkFileDialog 文件保存方法不起作用
【发布时间】:2011-07-23 04:51:45
【问题描述】:

我刚刚开始将 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")

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    我很清楚,当您调用 filesave 时,您的文件句柄 self.lastopenself.lastsave 已设置为与 False 等效的值。在您的 fileopenfilesave 函数退出后,您是否检查过它们是否仍然存在?用这种方式调试很简单,试试:

    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
    

    【讨论】:

    • 我试过了,值仍然存在,两个 False 检查返回 false。
    【解决方案2】:

    我想通了,我没有关闭文件。傻我。

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多