Save File Dialog in Tkinter (GUI Programming) – Python Tkinter Tutorial

Save File Dialog in Tkinter Python provides a vast number of libraries for GUI application development. Tkinter is the widely used library for GUI application development. Using the Tkinter library of python which carries large numbers of widgets, we can easily create a Graphical User Interface for our application.

Save File Dialog: Like other programming languages, Tkinter library of Python also provides functionality to perform the operation of open filesave file or directories. In this guide we are going to talk about save file dialog which is used when we have to save file or directories.

tkinter tutorial

In other programming languages like Java, php etc. we have to write full code for implementing save file dialog operation. But in Tkinter, this functionality is already defined.

Let’s see one example to understand this concept better

from tkinter import *
from tkinter import filedialog
#setting up parent window
root = Tk()

#function definition for opening file dialog
def savef():
    myFile = filedialog.asksaveasfile(mode='w', defaultextension='.txt')
    if myFile is None:
        return
    data = teditor.get(1.0,'end')
    myFile.write(data)
    myFile.close()

#creating text editor
teditor = Text(root, width=40, height=8)
teditor.pack(pady=10)

file_save = Button(root, text="Save file", command= savef)
file_save.pack(side=LEFT,padx=150)

root.geometry("350x200")
root.title("PythonLobby.com")
root.mainloop()

Output:
save file dialog in tkinter
example of save file dialog in tkinter
Detailed Explanation of Program

  • First, we have imported all the required libraries and modules of Tkinter using import *.
  • Then we have initialized root as an object for Tk() class for creating a root window.
  • Next we defined the savef() function which we will call on button click later.
  • In function definition we used filedialog library along with asksaveasfile function.
  • Here in function two parameter is passed i.e. mode=’w’ it means root directory where our current project file available and defaultextension=’.txt’ saving the file in text format.
  • Next we created one button. On button click the above function will be called and the function will perform the required operation.
  • Here we are also using text editor and the write file operation, so that it is more easy for you to understand the concept as well as its use case.
  • Rest below given code is for configuring our application layout i.e. width, height and the title.