Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick and easy file dialog in Python?

People also ask

What is file dialog in Python?

File dialogs help you open, save files or directories. This is the type of dialog you get when you click file,open. This dialog comes out of the module, there's no need to write all the code manually. Tkinter does not have a native looking file dialog, instead it has the customer tk style.


Tkinter is the easiest way if you don't want to have any other dependencies. To show only the dialog without any other GUI elements, you have to hide the root window using the withdraw method:

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

Python 2 variant:

import Tkinter, tkFileDialog

root = Tkinter.Tk()
root.withdraw()

file_path = tkFileDialog.askopenfilename()

You can use easygui:

import easygui

path = easygui.fileopenbox()

To install easygui, you can use pip:

pip3 install easygui

It is a single pure Python module (easygui.py) that uses tkinter.


Try with wxPython:

import wx

def get_path(wildcard):
    app = wx.App(None)
    style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
    dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style)
    if dialog.ShowModal() == wx.ID_OK:
        path = dialog.GetPath()
    else:
        path = None
    dialog.Destroy()
    return path

print get_path('*.txt')

If you don't need the UI or expect the program to run in a CLI, you could parse the filepath as an argument. This would allow you to use the autocomplete feature of your CLI to quickly find the file you need.

This would probably only be handy if the script is non-interactive besides the filepath input.


pywin32 provides access to the GetOpenFileName win32 function. From the example

import win32gui, win32con, os

filter='Python Scripts\0*.py;*.pyw;*.pys\0Text files\0*.txt\0'
customfilter='Other file types\0*.*\0'
fname, customfilter, flags=win32gui.GetOpenFileNameW(
    InitialDir=os.environ['temp'],
    Flags=win32con.OFN_ALLOWMULTISELECT|win32con.OFN_EXPLORER,
    File='somefilename', DefExt='py',
    Title='GetOpenFileNameW',
    Filter=filter,
    CustomFilter=customfilter,
    FilterIndex=0)

print 'open file names:', repr(fname)
print 'filter used:', repr(customfilter)
print 'Flags:', flags
for k,v in win32con.__dict__.items():
    if k.startswith('OFN_') and flags & v:
        print '\t'+k

Using tkinter (python 2) or Tkinter (python 3) it's indeed possible to display file open dialog (See other answers here). Please notice however that user interface of that dialog is outdated and does not corresponds to newer file open dialogs available in Windows 10.

Moreover - if you're looking on way to embedd python support into your own application - you will find out soon that tkinter library is not open source code and even more - it is commercial library.

(For example search for "activetcl pricing" will lead you to this web page: https://reviews.financesonline.com/p/activetcl/)

So tkinter library will cost money for any application wanting to embedd python.

I by myself managed to find pythonnet library:

  • Overview here: http://pythonnet.github.io/
  • Source code here: https://github.com/pythonnet/pythonnet

(MIT License)

Using following command it's possible to install pythonnet:

pip3 install pythonnet

And here you can find out working example for using open file dialog:

https://stackoverflow.com/a/50446803/2338477

Let me copy an example also here:

import sys
import ctypes
co_initialize = ctypes.windll.ole32.CoInitialize
#   Force STA mode
co_initialize(None)

import clr 

clr.AddReference('System.Windows.Forms')

from System.Windows.Forms import OpenFileDialog

file_dialog = OpenFileDialog()
ret = file_dialog.ShowDialog()
if ret != 1:
    print("Cancelled")
    sys.exit()

print(file_dialog.FileName)

If you also miss more complex user interface - see Demo folder in pythonnet git.

I'm not sure about portability to other OS's, haven't tried, but .net 5 is planned to be ported to multiple OS's (Search ".net 5 platforms", https://devblogs.microsoft.com/dotnet/introducing-net-5/ ) - so this technology is also future proof.