wxPython: Showing 2 Filetypes in wx.FileDialog
The other day on the wxPython IRC channel on freenode, one of the
members there asked if there was a way to make the wx.FileDialog display
more than one file type at a time. In the back of mind, I thought I had
seen a Microsoft product that could do it, but I’d never seen any
wxPython examples. In this short tutorial, you will learn how to do this
handy trick!
Here’s the code you’ll need:
import wx
wildcard = "Python source (*.py; *.pyc)|*.py;*.pyc|" \
"All files (*.*)|*.*"
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"Multi-file type wx.FileDialog Tutorial")
panel = wx.Panel(self, wx.ID_ANY)
btn = wx.Button(panel, label="Open File Dialog")
btn.Bind(wx.EVT_BUTTON, self.onOpenFile)
#----------------------------------------------------------------------
def onOpenFile(self, event):
"""
Create and show the Open FileDialog
"""
dlg = wx.FileDialog(
self, message="Choose a file",
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
paths = dlg.GetPaths()
print "You chose the following file(s):"
for path in paths:
print path
dlg.Destroy()
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
The key in this code is in the wildcard variable.
Look closely at it and you’ll notice that there’s some semi-colons in
there. The semi-colon in the second half of the first string is what we
care about. It tells the dialog to just show *.py and *.pyc files. Yes,
it really is that simple. The first half can be anything you want, but
it is recommended that you tell your users what file types they can
expect it to return.
That’s all there is to it. Be sure to keep this trick in the back of your mind when you go to create your own file dialogs. You might just need it!
Source: http://www.blog.pythonlibrary.org/2011/02/10/wxpython-showing-2-filetypes-in-wx-filedialog/
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)



