Search code examples
matplotlibtkintersavefiledialog

Is there a way of saving a matplotlib chart as a file in tkinter


I'm trying to save my graph but when I choose the file in the directory it says the filename is not defined

def save(): 

filename = asksaveasfile(initialfile = 'Untitled.png',defaultextension=".png",filetypes=[("All Files","*.*"),("Portable Graphics Format","*.png")])
plt.savefig(flename)

Solution

  • There are some typo errors. Here's you can fix this by doing this:

    def save():
        filename = asksaveasfilename(initialfile = 'Untitled.png',defaultextension=".png",filetypes=[("All Files","*.*"),("Portable Graphics Format","*.png")])
        plt.savefig(filename)
    

    At first there is indentation error in your save function. You wrote asksaveasfile which should be corrected as asksaveasfilename because we are just asking user to write the file name, not saving file there. And At last you wrote flename which is not defined anywhere else in program but I think you are trying to write filename cuz we get the filename from user in filename in previous line.