Creating Python button saves edited file
If you want a save function that silently overwrites the current file, the basic thing to do is save a reference to the file name/location that the user chose, and then the next time you save you can reuse it instead of asking for a new one. The following (taken from a program of mine) has a "plain" save function that checks if there's a save file name on record, and either uses it (if it exists) or goes to the "save as" function. The plain version happens to have a return
value so that it can interact with a load (open) function elsewhere in the program (asks the user whether to save unsaved work before loading a new file).
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 Falsedef 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 Falsedef 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.")