Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tkinter

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?

like image 796
Dhruv Mullick Avatar asked Feb 07 '23 09:02

Dhruv Mullick


1 Answers

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.

like image 165
en_Knight Avatar answered Feb 12 '23 10:02

en_Knight