Tuesday, October 7, 2025
HomeLanguagesPython | asksaveasfile() function in Tkinter

Python | asksaveasfile() function in Tkinter

Python provides a variety of modules with the help of which one may develop GUI (Graphical User Interface) applications. Tkinter is one of the easiest and fastest way to develop GUI applications.

While working with files one may need to open files, do operations on files and after that to save file. asksaveasfile() is the function which is used to save user’s file (extension can be set explicitly or you can set default extensions also). This function comes under the class filedialog.

Below is the Code:




# importing all files  from tkinter
from tkinter import * 
from tkinter import ttk
  
# import only asksaveasfile from filedialog
# which is used to save file in any extension
from tkinter.filedialog import asksaveasfile
  
root = Tk()
root.geometry('200x150')
  
# function to call when user press
# the save button, a filedialog will
# open and ask to save 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()


Output #1: Directory before saving any file (folder is initially empty)
asksaveasfile() function in Tkinter

Output #2: Dialogbox when user presses the save button (dialog box to save file is opened). You may see in the output Python file as default is selected.
Dialogbox when user presses the save button

Output #3: Directory after saving 2 Python files (one may also change the type of file)
Directory after saving 2 Python files

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32340 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6709 POSTS0 COMMENTS
Nicole Veronica
11872 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6829 POSTS0 COMMENTS
Ted Musemwa
7090 POSTS0 COMMENTS
Thapelo Manthata
6780 POSTS0 COMMENTS
Umr Jansen
6784 POSTS0 COMMENTS