Python create save button that saves an edited version to the same file(not save as) Python create save button that saves an edited version to the same file(not save as) tkinter tkinter

Python create save button that saves an edited version to the same file(not save as)


Here's a quick example of a save and save as function, with comments:

def save(self):    contents = self.textbox.get(1.0,"end-1c") #store the contents of the text widget in a str    try:                                       #this try/except block checks to        with open(self.f, 'w') as outputFile:  #see if the str containing the output            outputFile.write(contents)         #file (self.f) exists, and we can write to it,    except AttributeError:                     #and if it doesn't,        self.save_as()                         #call save_asdef save_as(self):    contents = self.textbox.get(1.0,"end-1c")    self.f = tkFileDialog.asksaveasfilename(   #this will make the file path a string        defaultextension=".z",                 #so it's easier to check if it exists        filetypes = (("ztext file", "*.z"),    #in the save function                     ("zytext", "*.zy")))    with open(self.f, 'w') as outputFile:        outputFile.write(contents)

There are other ways to do this, but this will work in a pinch. Just think about what the save function needs: text to save and a file to save in, and go from there.