创建Python按钮可保存已编辑的文件

时间:2015-04-15 17:04:10

标签: python function tkinter save

我是tkinter的新人,并且想知道是否有人可以指出我正确的方向。我想知道如何在没有saveasdialog的情况下覆盖以前保存的文件,就像实现实际的保存功能一样。我目前正在使用它为我的项目保存一个包含不同点的.txt文件。 保存为功能。我是否必须找到目录并以某种方式更改它?有没有更简单的方法来做到这一点? 到目前为止,对于save和saveas来说,这是我所拥有的:

def saveFile(self):
    method = self.method.current()
    try:
        with open(self.f,'w') as outputFile:
            if(method==0):
                method.write()
    except AttributeError:
        self.save_as

def saveFileAs(self):

    f = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
    method = self.method.current()
    #used to write to .txt file and does save
    if(method == 0):
    # f.write() to save to .txtfile

1 个答案:

答案 0 :(得分:1)

如果你想要一个静默覆盖当前文件的保存功能,基本的做法是保存对用户选择的文件名/位置的引用,然后下次保存时可以重复使用而不是询问换一个新的。以下(取自我的一个程序)有一个" plain"保存功能,检查记录中是否有保存文件名,并使用它(如果存在)或转到"另存为"功能。普通版本恰好具有return值,以便它可以与程序中其他位置的加载(打开)函数进行交互(询问用户是否在加载新文件之前保存未保存的工作)。

def save_plain(self, *args):
    """
    A plain save function. If there's no preexisting file name,
    uses save_as() instead.
    Parameter:
        *args: may include an event
    """
    if self.savename: # if there's a name
        self.save(self.savename) # then use it
    elif self.save_as(): # else, use save_as instead
        return True # successful save returns True
    return False # else, return False

def save_as(self, *args):
    """
    A save as function, which asks for a name and only retains it if it was given
    (canceling makes empty string, which isn't saved).
    Parameter:
        *args: may include an event
    """
    temp = filedialog.asksaveasfilename(defaultextension=".txt", \
    filetypes=(('Text files', '.txt'),('All files', '.*'))) # ask for a name
    if temp: # if we got one,
        self.savename = temp # retain it
        self.save(temp) # and pass it to save()
        return True
    return False

def save(self, filename):
    """
    Does the actual saving business of writing a file with the given name.
    Parameter:
        filename (string): the name of the file to write
    """
    try: # write the movelist to a file with the specified name
        with open(filename, 'w', encoding = 'utf-8-sig') as output:
            for item in self.movelist:
                output.write(item + "\n")
        self.unsaved_changes = False # they just saved, so there are no unsaved changes
    except: # if that doesn't work for some reason, say so
        messagebox.showerror(title="Error", \
        message="Error saving file. Ensure that there is room and you have write permission.")