How to target a generated plot for saving using Tkinter's asksaveasfile function?


How can I use the asksaveasfile function to target the plot I generated so the user can enter a custom file name for the generated plot? I have other functions setup to read data and generate the plots, but I want to make it so the GUI in which all of my work is being done in will bring up a window to save the generated plot through user input rather than me simply hard-coding a name for the generated plot.

from tkinter import * # all modules imported, most remain unused atm from tkinter import messagebox from tkinter import ttk from tkinter.filedialog import askopenfilename from tkinter.filedialog import askopenfile from tkinter.filedialog import asksaveasfile import numpy as np import matplotlib.pyplot as plt from PIL import ImageTk def UseData(): data1, data2 = OpenFile() plt.figure(1) plt.plot(data1, data2) plt.title('Variable') plt.ylabel('Some Units') plt.xlabel('More Units') plt.tight_layout() result = messagebox.askyesno("Window-1", "Data processed. \nWould you like to save the figure?") if result== True: asksaveasfile(filetypes=(("PNG Image", "*.png"),("All Files", "*.*")), defaultextension='.png', title="Window-2") # a = 'picture.png' # plt.savefig(a) messagebox.showinfo("Window-3", "Plot Saved.") # Conf. message of saving

The OpenFile function works perfectly fine for importing the data I am interested in, so that is of no concern. The issue I am running into is a part of the if statement I have at the bottom portion, where it essentially contains A.) The way I want to save the plot (via the asksaveasfile command) and B.) Hard-coding in a file name. Is there a way for said command to target a specific plot that has been generated and save it? If not then that is fine, but I could not figure out a way to get that to work.


Use asksaveasfilename instead, as it returns the path to the selected/created file(by calling native GUI if possible, which allows creating a file if it doesn't exist). So all you need to do is simply:

a = asksaveasfilename(filetypes=(("PNG Image", "*.png"),("All Files", "*.*")), defaultextension='.png', title="Window-2") plt.savefig(a)

But to be safe also check if there is a filename <em>after</em> that window, as the user may "Cancel":

a = asksaveasfilename(filetypes=(("PNG Image", "*.png"),("All Files", "*.*")), defaultextension='.png', title="Window-2") if a: plt.savefig(a)