1

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.

imxitiz
  • 3,920
  • 3
  • 9
  • 33
Totocode
  • 19
  • 4

1 Answers1

2

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.

Ake
  • 805
  • 1
  • 3
  • 14