Tkinter File Dialog

Salman Mehmood Mar 04, 2022
  1. File Dialog in Tkinter Library of Python
  2. Use the askopenfilename() Method to Browse File With the Tkinter Dialog Box in Python
  3. Use the asksaveasfile() Method to Save the File With the Tkinter Dialog Box in Python
  4. Use the askdirectory() Method of Tkinter to Select Directory in Python
Tkinter File Dialog

This tutorial will demonstrate how to create the file dialog using the filedialog Tkinter class and explore several methods.

File Dialog in Tkinter Library of Python

Python Tkinter library provides many dialog boxes that you can use for working with files. By developing in the Tkinter, you do not need to create standard dialog boxes yourself.

The file dialog includes an open file dialog box, a save file box, and more.

File dialog helps you to open save files or directories. You get this kind of dialog box when you click a file to open it.

The filedialog class helps create dialog boxes; no need to write the code from scratch.

Use the askopenfilename() Method to Browse File With the Tkinter Dialog Box in Python

Options Explanation
title The name could be set on the dialog box using this option.
initialdir Takes a path to open a dialog box in a specific directory.
filetypes This option takes a tuple. You can pass a specific file name and extension.
defaultextension We do not specify the file extension. If we pass this option in the method, the dialog box will automatically select the extension passed to the value. This option only works with save dialog.

We can use the askopenfilename() method to upload files. This method returns a file location.

In this example, we created an open() function. The open() function helps a dialog box to appear using the askopenfilename method.

from tkinter import Tk, filedialog, Button, Label
from PIL import ImageTk, Image

root = Tk()
root.geometry("400x400")


def open():
    # Create a dialog box
    root.file_name = filedialog.askopenfilename(
        initialdir="your directory path",
        title="file uploader",
        filetypes=(("jpg files", "*.jpg"), ("all files", "*.*")),
    )
    # takes path that is selected by dialog box
    selected_image = Image.open(root.file_name)
    # resize image
    selected_image = selected_image.resize((300, 205), Image.ANTIALIAS)
    # displays an image
    root.image = ImageTk.PhotoImage(selected_image)
    selected_image_label = Label(root, image=root.image).pack()


btn = Button(root, text="upload image", command=open).pack()
root.mainloop()

askopenfilename method

Use the asksaveasfile() Method to Save the File With the Tkinter Dialog Box in Python

If you read this, you are already familiar with the save as dialog box. In this case, we are using the asksaveasfile() method.

This method lets you save a file on the desired location.

from tkinter import *
from tkinter import filedialog


def saveFile():
    file = filedialog.asksaveasfile(
        initialdir="your directory path",
        defaultextension=".txt",
        filetypes=[
            ("Text file", ".txt"),
            ("HTML file", ".html"),
            ("All files", ".*"),
        ],
    )
    if file is None:
        return
    # get the text
    filetext = str(text.get(1.0, END))
    file.write(filetext)
    file.close()


win = Tk()
button = Button(text="save", command=saveFile)
button.pack()
# create text box
text = Text(win)
text.pack()
win.mainloop()

The saveFile() method helps get a text from the Text widget and lets you select the location where you want to save this file.

asksaveasfile method

We can see the file is saved in the given location.

output text file

Use the askdirectory() Method of Tkinter to Select Directory in Python

This method only selects a directory. This method does not allow the selection of any file.

from tkinter import Tk, filedialog, Button

win = Tk()


def openDirectory():
    dir_path = filedialog.askdirectory(
        initialdir="your directory path", title="Select directory"
    )


btn = Button(win, text="upload image", command=openDirectory).pack()

win.mainloop()

You can put r before the path if you get a Unicode error. For example, r"your directory path".

askdirectory method

We have discussed majorly useable methods, but still, more methods exist in the filedialog class. Click here to read about more methods.

Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn