How Can I Use The Same Dialog Box In Tkinter To Browse And Select Files And Directories?
Solution 1:
I don't think so. There is no built-in class to do it easily
Investigation
If you look at the tkFileDialog
module's source code, both the Open
and the Directory
classes inherit from _Dialog
, located in tkCommonDialog
.
Good so far; these classes are simple and only extend two methods. _fixresult
is a hook that filters based on your options (promising), and _fixoptions
adds the right tcl parameters (like initial directory).
But when we get to the Dialog class (parent of _Dialog), we see that it calls a tcl command by a given name. The names built-in are "tk_getOpenFile" and "tk_chooseDirectory". We don't have a lot of python-level freedom of the command after this. If we go to see what other tcl scripts are avaliable, we are disappointed.
Looks like your options are
ttk::getOpenFile
ttk::getSaveFile
ttk::chooseDirectory
ttk::getAppendFile
Conclusion
Rats! Luckily, it should be quite easy for you to make your own dialog using listboxes, entry fields, button, (and other tk-builtins), and the os module.
Simple Alternative
From your comments, it looks like a viable simple work-around might be to use
directory = os.path.dirname(os.path.realpath(tkFileDialog.askopenfilename()))
They'll have to select a file, but the "Open" button will "return a path", in the sense that the path is computed from the file location
But I really want it!
If for some reason you really want this behaviour but don't want to remake the widget, you can call tcl scripts directly. It may be possible to copy the code from getOpenFile and provide more loose arguments that allow for selecting a more generic object. This isn't my speciality and seems like a really bad idea, but here is how you call tcl directly and here is where you can learn more about the underlying commands.
Solution 2:
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.
Post a Comment for "How Can I Use The Same Dialog Box In Tkinter To Browse And Select Files And Directories?"