python logo

wx.filedialog


Python hosting: Host, run, and code Python in the cloud!

Every desktop application that deals with file management usually comes with a built-in file dialog for opening or saving files. The essence of a file dialog is its complexity: not only does it incorporate multiple widgets like buttons, labels, and location selectors, but its appearance varies across platforms like Mac OS and Windows.

If you’re keen on developing GUI applications using Python, the wxPython module simplifies the creation of these file dialogs. With just a few lines of code, you can provide a native-looking file dialog for your application.

wxPython Open File Dialog

wxPython File Dialog Implementation

The following code showcases how to design a native-looking file dialog with wxPython:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python

import wx

def onButton(event):
print "Button pressed."

app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)

# Creating the open file dialog
openFileDialog = wx.FileDialog(frame, "Open", "", "",
"Python files (*.py)|*.py",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
openFileDialog.ShowModal()
print(openFileDialog.GetPath())
openFileDialog.Destroy()

Using wxPython, the method to call and create a file dialog is wx.FileDialog(). The signature for this method includes parameters like the parent, message, default directory, default file, wildcard patterns, styles, and position:

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

In this particular instance, no default directory or file has been specified. Once the file dialog is created, it can be displayed using the ShowModal() method:

1
openFileDialog.ShowModal()

Additionally, if you need to fetch the full path of the selected file, the openFileDialog.GetPath() method proves handy.

For those aiming to enhance their GUI application development skills in Python, you might find the Creating GUI Applications with wxPython course particularly beneficial.

← Back Next →






Leave a Reply: