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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With