How can I use the same dialog box in Tkinter to browse and select files and directories?

Viewed 3158

I am using Tkinter for building a GUI for a python script. I need a button which opens up a dialog box which allows me to select both files and directories. Till now, I've come across

tkFileDialog.askdirectory(parent=root, title=dirtext1)

which allows just to select directories in the dialog box and,

tkFileDialog.askopenfilename(parent=root, title=filetext)

which allows me to just select files. As of now, I access these dialog boxes using separate buttons, each of which calls one of these functions. Is there anyway to select either a file or a folder using a single dialog box?

2 Answers

I've had a similar issue. In the end, I used askopenfilenames() (plural) and split the path from the files. Then with a radiobutton, ask the user to choose if they want to process all the files in the directory, or just those they selected.

filetypes = [('All files', '*.*'), ('CSV files', '*.csv'),]
data_list = askopenfilenames(title='Select folder', filetypes=filetypes)
data_dir = data_list[0].rsplit('/', 1)[0]

I mention it because askopenfilenames() doesn't get suggested much, but is closer to selecting a folder, as can ctrl+A all files.

Related