wxPython file dialog

Nearly every desktop application that can open one or more files has a file dialog.

An open file dialog may seem like a very complicated window to create: it contains buttons, locations, labels and many more widgets. Moreover, the appearance of this open file dialog looks different on every platform: Mac OS, Windows and so on.

The wxPython module comes with open file dialogs, which can be created with a few functions calls.

wxPython Open File Dialog

wxPython file dialog

The example below creates a file dialog with a native appearance using wxPython:

import wx
def onButton(event):
    print "Button pressed."
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
# Create open file dialog
openFileDialog = wx.FileDialog(frame, "Open", "", "", 
                                      "Python files (*.py)|*.py", 
                                       wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

To create a file dialog with wxPython we can simply call wx.FileDialog().
The definition of this method is: (parent, message, defaultDir, defaultFile, wildcard, style, pos)
We call this method with the arguments:

wx.FileDialog(frame, "Open", "", "","Python files (*.py)|*.py",wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

(no default dir or default file is specified).

The method showModal() displays the window:


The command openFileDialog.GetPath() returns the full path to the file if one is selected.