Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select files and folders with Tkinter's filedialog

I want to select files and folders with filedialog in Tkinter(Python). I try using askdirectory and askopenfilenames. But I can’t find a special dialog in documentation.
https://docs.python.org/3/library/dialog.html

This is my sample code:

root = tk.Tk()
root.withdraw()

# one way
files_and_directories = filedialog.askopenfilenames(parent=root, title="Select files and folders", multiple=True)

# another way
files_and_directories = filedialog.askdirectory(parent=root, title='Select files and folders', multiple=True)

The problem is that askopenfilenames and askdirectory don’t return a list with the files and the folders that I select.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By default, the askopenfilenames and askdirectory functions return only the file paths or directory path respectively, and not both in a single call.

root = tk.Tk()
root.withdraw()

# select files
files = filedialog.askopenfilenames(parent=root, title="Select files", multiple=True)

# select directories
dirs = filedialog.askdirectory(parent=root, title='Select directories', multiple=True)

# combine results into a single list
files_and_dirs = list(files) + list(dirs)

askopenfilenames and askdirectory both return tuples, which is why we convert them to lists before concatenating them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading