Creating a simple file dialog box with Tkinter - Have you come to a point when you want to avoid running your Python scriot in the same folder as your files you want to work with? Do you find it annoying to input the file paths each time? Using Tkinter, you can create a native file dialog, that easily returns multiple files as a list or any other data type of your choosing. Check out the code below!
Let's walk through the code. First, we start with the shebang. I use a lot of Scandinavian letters, so I usually also import utf-8. Moving on to the imports, where we import Tkinter and the filedialog and messagebox. We also import sys so that we can exit from our messagebox. We define the function ask_for_input_files, and create an empty placeholder named files. We then enter a while loop that will go on until we have selected our files. If the user wants to exit, pressing the Cancel button generates a messagebox, asking if the user wants to exit the application. When we have our files we return them as a list. Feel free to modify as needed. Remember to create a root window and also to withdraw it. Otherwise, the main frame is shown in the background, which looks a bit funky.
#! python3 # -*- coding: utf-8 -*- """ File dialog that imports selected files. Returns file paths in a list. Coded by Conny Söderholm """ ### IMPORTS ### import tkinter as tk from tkinter import filedialog, messagebox import sys def ask_for_input_files(): """ Gets all files that need to be converted from the user and returns them as a list. Remember to create a tk.Tk() app first! """ files = None while files == None: files = filedialog.askopenfilenames(title='Choose files', filetypes = (("All files", "*.*"),("Text files", "*.txt") )) if not files: answer = messagebox.askquestion("Exit program", "Do you want to exit??", icon='question') if answer == "yes": sys.exit() if answer == "no": files = None return list(files) if __name__ == "__main__": ### Load Tkinter and greet user root = tk.Tk() root.withdraw() files = ask_for_input_files() print(type(files)) print(files)
You can find more information about Tkinter from Python.org. I hope that this helps you to start selecting files more easily! If you want to see how to create an Hello World application in Tkinter, check out my post here. Happy coding!
[…] We will create a program that first asks for the folder name file with a filedialog. See an earlier post for more information about filedialogs in Tkinter. The program will then ask where to create the […]
[…] the user where the directory we want to search is. If the user presses cancel on the askdirectory filedialog we exit the application. We then add a slash to the end of the folder name if needed. Next, we get […]