This blog post will explain how to select multiple files with a tkinter file dialog box with python.
The tkinter library is imported so that a graphical user interface can be coded. The filedialog library from tkinter has to be imported because it will be used to create a file dialog box.
import tkinter as tk
from tkinter import filedialog as fd
A tkinter object is created and stored in the variable root.
root = tk.Tk()
The statement below will hide the main window since load and save file dialogs don’t need the window.
root.withdraw()
The filetypes variable is set to two audio file extensions.
filetypes = (
('mp3', '*.mp3'),
('m4a', '*.m4a')
)
The function askopenfilenames will retrieve a selection of file names and store it in the variable filenames as a list.
filenames = fd.askopenfilenames(
title='Open multiple files.',
initialdir='/',
filetypes=filetypes)
A simple for loop will print out the filenames stored in the variable filenames.
for x in filenames:
print(x)
The root object is destroyed.
root.destroy()
A main loop is executed for the program.
root.mainloop()
This is what the whole source code looks like.
import tkinter as tk
from tkinter import filedialog as fd
root = tk.Tk()
root.withdraw()
filetypes = (
('mp3', '*.mp3'),
('m4a', '*.m4a')
)
filenames = fd.askopenfilenames(
title='Open multiple files.',
initialdir='/',
filetypes=filetypes)
for x in filenames:
print(x)
root.destroy()
root.mainloop()