Python | asksaveasfile () function in Tkinter



When working with files, you may need to open files, perform file operations, and then save the file.  asksaveasfile () — this is the function that is used to save the user file (the extension can be set explicitly or you can set the default extensions as well) This function refers to class filedialog .

Below is the code:

# import all files from tkinter

from tkinter import *  

from tkinter import ttk

 
# only import asksaveasfile from filedialog
# which is used to save the file in any extension

from tkinter.filedialog import asksaveasfile

  

root = Tk ()

root.geometry ( `200x150` )

 
# function to call when user clicks
# save button, dialog
# open and ask to save the file

def save ():

  files = [( `All Files` , `*. *` ), 

( `Python Files` , `*. py` ),

( `Text Document` , ` * .txt` )]

file = asksaveasfile (filetypes = files, defaultextension = files)

 

btn = ttk.Button (root, text = `Save` , command = lambda : save ())

btn.pack (side = TOP, pady = 20 )

 
mainloop ()

Conclusion # 1: Directory before saving any file (folder is initially empty)

Exit # 2: dialog window when the user clicks the save button (opens a dialog box to save the file). You can see in the output the default Python is selected. 

Output # 3: Directory after saving 2 Python files ( you can also change the file type)