filedialog.asksaveasfile create a modal, native look-and-feel dialog for user to save file in local system. .
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile
Displaying save as file browser to Save file in Tkinter window using filedialog asksaveasfilename
Here is the code to open one file browser dialog box and then user has to enter the file name. Sample data ( small string ) will be saved inside the file.
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile
my_w = tk.Tk()
my_w.geometry("400x300") # Size of the window
my_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Save File',width=30,font=my_font1)
l1.grid(row=1,column=1)
b1 = tk.Button(my_w, text='Save',
width=20,command = lambda:save_file())
b1.grid(row=2,column=1)
def save_file():
file = filedialog.asksaveasfilename(
filetypes=[("txt file", ".txt")],
defaultextension=".txt")
fob=open(file,'w')
fob.write("Welcome to plus2net")
fob.close()
my_w.mainloop() # Keep the window open
Data is saved in the file
When user cancels the file window
After opening the file browser the user may use the cancel button to close the operation, to handle this we have added the if file: in above code. The else part of the code will display the message.
def save_file():
file = filedialog.asksaveasfilename(
filetypes=[("txt file", ".txt")],
defaultextension=".txt")
if file: # user selected file
fob=open(file,'w')
fob.write("Welcome to plus2net")
fob.close()
else: # user cancel the file browser window
print("No file chosen")
options : initialdir
We can set the initial directory to be show to user by default. User can change to any other location.
If the file is already available then one confirmation window asking to overwrite the fill will be displayed. This message we can manage and if you don't want to show the dialog box then set the confirmoverwrite to False. By default this value is True ( To display dialog box )
difference between asksaveasfile() and asksaveasfilename()
The function asksaveasfilename() returns the selected file name. ( path as string ).
The function asksaveasfile() returns the opened file object in given mode. ( mode='w')
In above code both can be used and watch the commented part of the code below for comparison of both functions. In both cases output is same.
We will create one user data entry box in the window and on click of the Save button the text entered in the entry box will be saved into one text file using the filedialog. Save data entered by user in Tkinter window »
Project : GUI Text Editor
Text Editor with all file handling operations like New, Open., Save, Save As and Close to add or update data of the file. The tkinter filedialog is used to display file handling dialog boxes and Menu is used to execute various functions to manage a file. Tkinter Text Editor to Manage File Operations »