Change language

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)

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically