Tkinter tkFileDialog module in Python

Hello coders, this tutorial deals with a program to open and save a file using Tkinter. But if you don’t know the basics of the Tkinter module then please refer this link Introduction to Tkinter module in Python. Tkinter tkFileDialog module in Python is described here.

Functions in tkFileDialog

tkinter.filedialog module provides built-in functions for accessing and creating a file in your system.

filedialog.askopenfilename(), filedialog.asksaveasfilename(), etc.

By using these functions we can manually open and save a file whenever it is needed.

Now let us code for opening a file-

Firstly we need to use two import statements i.e Tkinter package to access all GUI tool kit of Tkinter and another one is filedialog package under Tkinter for the popup window. Now let’s import the packages.

from tkinter import filedialog,Tk

To get a frame, we need to store that in a variable root(example) by calling Tk() function.

root=Tk()

Now we need to use a method filedialog.askopenfilename(initialdir, title, filetypes). Here the first parameter is for opening the specified initial directory, the second parameter is for the title of the window and finally, the third one is for specifying the type of files.

filetypes need to be defined by the syntax ((“Name of file type 1”, “Extension(i.e like *.exe)”),(“Name of the file type 2″,”Extension(i.e like *.png)”)).

root.file_name=filedialog.askopenfilename(initialdir ="C:", title="Open File", filetypes=(("png files","*.png"),("jpeg files","*.jpg"),("all files","*.*")))

And we can add a print() statement to find the location of the selected file.

Final Code:

from tkinter import filedialog,Tk

root = Tk()
root.file_name=filedialog.askopenfilename(initialdir ="C:", title="Open File", filetypes=(("png files","*.png"),("jpeg files","*.jpg"),("all files","*.*")))
print (root.file_name)

Output:

This is the pop-up after executing the program
This is the pop-up after executing the program

Selecting a file from window

Tkinter

Output on python IDLE

Tkinter tkFileDialog module in Python

Now let us come to code for saving a file-

Same as for opening the file but just one difference is that instead of filedialog.askopenfilename() we are using a method filedialog.asksaveasfilename(). 

Final Code:

from tkinter import filedialog,Tk


root = Tk()
root.file_name=filedialog.asksaveasfilename(initialdir ="C:", title="Open File", filetypes=(("png files","*.png"),("jpeg files","*.jpg"),("all files","*.*")))
print (root.file_name)

Output:

filedialog.asksaveasfilename()

This is how this module works, for any queries please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *