Open a file dialog with a python GUI (tkinter.filedialog)

This is a memo of the procedure to use the file dialog with tkinter.

Select a folder

You can use tkinter.filedialog.askdirectory to open a dialog to select a folder. Specify the initial directory with initialdir.

python


import tkinter.filedialog
iDir = os.path.abspath(os.path.dirname(__file__))
folder_name = tkinter.filedialog.askdirectory(initialdir=iDir)

Select a file

You can open a file dialog with tkinter.filedialog.askopenfilename. Specify the candidate file pattern with filetypes, and specify the first directory to open with initialdir. If you want to select multiple files, use tkinter.filedialog.askopenfilenames.

python


import tkinter.filedialog
fTyp = [("", "*")]
iDir = os.path.abspath(os.path.dirname(__file__))
file_name = tkinter.filedialog.askopenfilename(filetypes=fTyp, initialdir=iDir)

You can specify the file extension. Give in the order of heading and pattern.

python


fTyp = [("data file", "*.csv;*.xlsx;*.xls")]

You can also select by partial match of the file name.

python


fTyp = [("log file", "log*")]

Example of use

When actually using it, I think it's best to use it like this.

python


import os
import tkinter as tk
import tkinter.filedialog

class TkinterClass:
    def __init__(self):
        root = tk.Tk()
        root.geometry("500x350")

        button = tk.Button(root, text='Open file dialog', font=('', 20),
                           width=24, height=1, bg='#999999', activebackground="#aaaaaa")
        button.bind('<ButtonPress>', self.file_dialog)
        button.pack(pady=40)

        self.file_name = tk.StringVar()
        self.file_name.set('Not selected')
        label = tk.Label(textvariable=self.file_name, font=('', 12))
        label.pack(pady=0)

        button = tk.Button(root, text='Open folder dialog', font=('', 20),
                           width=24, height=1, bg='#999999', activebackground="#aaaaaa")
        button.bind('<ButtonPress>', self.folder_dialog)
        button.pack(pady=40)

        self.folder_name = tk.StringVar()
        self.folder_name.set('Not selected')
        label = tk.Label(textvariable=self.folder_name, font=('', 12))
        label.pack(pady=10)

        root.mainloop()

    def file_dialog(self, event):
        fTyp = [("", "*")]
        iDir = os.path.abspath(os.path.dirname(__file__))
        file_name = tk.filedialog.askopenfilename(filetypes=fTyp, initialdir=iDir)
        if len(file_name) == 0:
            self.file_name.set('Canceled selection')
        else:
            self.file_name.set(file_name)

    def folder_dialog(self, event):
        iDir = os.path.abspath(os.path.dirname(__file__))
        folder_name = tk.filedialog.askdirectory(initialdir=iDir)
        if len(folder_name) == 0:
            self.folder_name.set('Canceled selection')
        else:
            self.folder_name.set(folder_name)


if __name__ == '__main__':
    TkinterClass()
Let's try

Digression

Works well import


import tkinter as tk
import tkinter.filedialog
tk.filedialog.askdirectory(initialdir=iDir)

Import that doesn't work


import tkinter as tk
tk.filedialog.askdirectory(initialdir=iDir)

why! ??

Recommended Posts

Open a file dialog with a python GUI (tkinter.filedialog)
Let's make a GUI with python.
Creating a simple PowerPoint file with Python
I made a configuration file with Python
How to read a CSV file with Python 2/3
I made a GUI application with Python + PyQt5
Create a GUI executable file created with tkinter
File operations with open — "../"
You can easily create a GUI with Python
Create a Photoshop format file (.psd) with python
Read line by line from a file with Python
Run a Python file with relative import in PyCharm
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a 2d CAD file ".dxf" with python [ezdxf]
Draw netCDF file with python
[GUI with Python] PyQt5-Layout management-
Make a fortune with Python
Create a directory with python
[GUI with Python] PyQt5 -Preparation-
Download csv file with python
[GUI with Python] PyQt5 -Paint-
Select file in dialog with python → Display file name in message box
Creating a GUI as easily as possible with python [tkinter edition]
[Python] What is a with statement?
Extract the xz file with python
Operate a receipt printer with python
A python graphing manual with Matplotlib.
[Python] Write to csv file with Python
Create a python GUI using tkinter
[Automation with python! ] Part 1: Setting file
Implemented file download with Python + Bottle
Build a deb file with Docker
Solve ABC166 A ~ D with Python
Output to csv file with Python
Create a virtual environment with Python!
Open UTF-8 with BOM in Python
Create an Excel file with Python3
I made a fortune with Python.
Create a binary file in Python
Building a virtual environment with Python 3
[GUI with Python] PyQt5-Drag and drop-
Solve ABC168 A ~ C with Python
Make a recommender system with python
[Python] Generate a password with Slackbot
Solve ABC162 A ~ C with Python
Solve ABC158 A ~ C with Python
Let's make a graph with python! !!
[Automation with python! ] Part 2: File operation
[GUI with Python] PyQt5 -Custom Widget-
Open the file with the default app
Draw a graph with PySimple GUI
[Python] Inherit a class with class variables
I made a daemon with Python
Write a batch script with Python3.5 ~
Create a file uploader with Django
Read a file in Python with a relative path from the program
The idea of feeding the config file with a python file instead of yaml
[Python] Read a csv file with a large data size using a generator
[ROS2] How to play a bag file with python format launch
Try adding a wall to your IFC file with IfcOpenShell python
[Pyenv] Building a python environment with ubuntu 16.04