Join Club ShowMeDo to Learn Python!

This series is a part of Club ShowMeDo. Click to learn why you should join our club with a simple monthly subscription.

  • We teach Python and all the cool modules
  • Topics include beginner Python, GUIs, Web and Desktop Apps
  • Long, specially crafted video tutorials just for you
  • Club video tutorials extend our normal Free content
  • Save your time - we've done the research for you
  • Keep your skills up-to-date
  • Learn at your own pace, everything you need is shown to you
  • Over 12 hours of archived material are waiting for you in the club

Name: [002] Ian Ozsvald
Member: 104 months
Authored: 181 videos
Description: I am the co-founder of ShowMeDo (see http://showmedo.com/about), author of `The Screencasting Handbook <http://thescreencastinghandbook.com>`_ and the founder of the professional screencast production company `ProCasts <http://procasts.co.uk>`_: .. image:: http://procasts.co.uk/media/procasts_sma ...

Create a wx.FileDialog() File-Opener [ID:529] (5/14)

in series: Build a wxPython Image Viewer

(Showmedo is undergoing major changes. To report any problems viewing the videos please email us and include browser and OS specifics. Cheers - Kyran.)

To display a user's image we'll need to ask for a file-name. We use the wx.FileDialog() - configured to act as a file-opener dialog - to get a full pathname from the user.

We extend the OnOpen method so it calls the file dialog and if a user selects a file then we set the Frame's title with .SetTitle and show how to enable a busy-mouse-pointer with BeginBusyCursor and EndBusyCursor. The dialog is shown using .ShowModal() and we clean-up after with dlg.Destroy().

Finally we customise the FileDialog with a custom filter so it only shows us image-files rather than all files.

Download 3 test images in a zip file. The necessary source code is shown below in the Source Code tab.

#import os
import wx

MAIN_WINDOW_DEFAULT_SIZE = (300,200)

class Frame(wx.Frame):
    
    def __init__(self, parent, id, title):
        style=wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER) # XOR to remove the resizeable border        
        wx.Frame.__init__(self, parent, id, title=title, size=MAIN_WINDOW_DEFAULT_SIZE, style=style)
        self.Center() # open in the centre of the screen
        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour('White') # make the background of the window white

        self.CreateMenuBar()

    def CreateMenuBar(self):
        "Create a menu bar with Open, Exit items"
        menuBar = wx.MenuBar()
        # Tell our Frame about this MenuBar
        self.SetMenuBar(menuBar)
        menuFile = wx.Menu()
        menuBar.Append(menuFile, '&File')
        # NOTE on wx ids - they're used everywhere, we don't care about them
        # Used to handle events and other things
        # An id can be -1 or wx.ID_ANY, wx.NewId(), your own id
        # Get the id using object.GetId()
        fileOpenMenuItem = menuFile.Append(-1, '&Open Image', 'Open a picture')
        #print "fileOpenMenuItem.GetId()", fileOpenMenuItem.GetId()
        self.Bind(wx.EVT_MENU, self.OnOpen, fileOpenMenuItem)

        # add a 'mirror' option, disable it for now
        # we add mirrorMenuItem to self so that we can reference it later
        #self.mirrorMenuItem = menuFile.Append(-1, '&Mirror Image', 'Mirror the image horizontally')
        #self.mirrorMenuItem.Enable(False) # we can't mirror an image until we've loaded one in, so start with 'mirror' disabled
        #self.Bind(wx.EVT_MENU, self.OnMirrorImage, self.mirrorMenuItem)
        
        # create a menu item for Exit and bind it to the OnExit function       
        exitMenuItem = menuFile.Append(-1, 'E&xit', 'Exit the viewer')        
        self.Bind(wx.EVT_MENU, self.OnExit, exitMenuItem)
        
        # add a Help menu with an About item
        #menuHelp = wx.Menu()
        #menuBar.Append(menuHelp, '&Help')
        #helpMenuItem = menuHelp.Append(-1, '&About', 'About screen')
        #self.Bind(wx.EVT_MENU, self.OnAbout, helpMenuItem)

    def OnOpen(self, event):
        "Open an image file, set title if successful"
        # Create a file-open dialog in the current directory
        
        #filters = 'Image files (*.gif;*.png;*.jpg)|*.gif;*.png;*.jpg'
        #dlg = wx.FileDialog(self, message="Open an Image...", defaultDir=os.getcwd(), 
        #                    defaultFile="", wildcard=filters, style=wx.OPEN)
        
        dlg = wx.FileDialog(self, message="Open an Image...", defaultDir=os.getcwd(), 
                            defaultFile="", style=wx.OPEN)
        
        # Call the dialog as a model-dialog so we're required to choose Ok or Cancel
        if dlg.ShowModal() == wx.ID_OK:
            # User has selected something, get the path, set the window's title to the path
            filename = dlg.GetPath()
            print filename
            #self.SetTitle(filename)
            #wx.BeginBusyCursor()            
            #wx.EndBusyCursor()
                        
        dlg.Destroy() # we don't need the dialog any more so we ask it to clean-up
        
    def OnExit(self, event):
        "Close the application by Destroying the object"
        # TRY add in your own print call here
        self.Destroy() # SHOW HELP SIDEBAR
        
    
class App(wx.App):
    
    def OnInit(self):
        self.frame = Frame(parent=None, id=-1, title='Image Viewer')
        self.frame.Show()
        self.SetTopWindow(self.frame)
        return True
    
if __name__ == "__main__":       
    # make an App object, set stdout to the console so we can see errors
    app = App(redirect=False)
        
    app.MainLoop()

Got any questions?

Get answers in the ShowMeDo Learners Google Group.

Video statistics:

  • Video's rank shown in the most popular listing
  • Video plays: 175 (since July 30th)
  • Plays in last week: 0
  • Published: 78 months ago

Thank-yous, questions and comments

If this video tutorial was helpful please take some time to say thank-you to the authors for their hard work. Feel free to ask questions. Let the author know why their video tutorial was useful - what are you learning about? Did the video tutorial save you time? Would you like to see more?

You may also want to see our ShowMeDo Google Group to speak to our active users and authors.

Your email address will not be published.

Show some quick comments >>








All comments excluding tick-boxed quick-comments

The video was well presented and I actually find myself learning the concepts of general GUI development faster than I expected. Also I'm wanting to create a simple address book application that stores information in a small SQLite database. I look forward to the next presentations.


8. anonymous Wed, 03 Jun 2009 23:38

important topic


How do you implement the Save Dialog

Thanks


you asked what we were interested in trying to build, I work for a Cable Access TV station, we use a commercial package (software & hardware) to play image files on the tv channel when we are not broadcasting a show. Most of these images are just jpeg's showing some community event information, but we also show RSS feeds, text tickers, some short commercial like video's. I would like to recreate this functionality in my own program. Python seems like a good approach. I believe I need wxpython so I can split the screen into different portions (example have a ticker at the bottom). I am them going to write a web based scheduling program to control when each image "bulletin" gets shown. I think I should also be able to get it to display flash files as well. My concern is the time to transition between a bulletin being displayed and then get a media player on the screen without the TV viewers seeing a gap. I will build it a little at a time. No body has a software only product like this available or if they do it is a subscription service.


a bit slow, so I keep clicking forward. But good explanations and I do learn a lot.


Hi Shane, sorry for hear again that you're having trouble with Mac OS X - I'd have thought that file-dialogs would work just fine everywhere! I'll keep my ears open.

You might want to ask on the wxpython-users (http://wxpython.org/maillist.php) mail list?

Cheers,

Ian.


There have been a few times where I get lost because of apparent platform differences. In osx, the menubar is quite different and the filters don't seem to work at all.


Good job although I'd say that your first couple of videos in this series were a tiny bit better.

Nevertheless, this is still one of the best tutorial videos I've ever seen and trust me: I've seen lot's of 'em!

Lucas


Video published, thanks for contributing to ShowMeDo


Showmedo is a peer-produced video-tutorials and screencasts site for free and open-source software (FOSS)- with the exception of some club videos, the large majority are free to watch and download.

how to help » about » faq »

Educating the Open-source Community With Showmedo

Although as important as the software it supports, education and documentation are relatively neglected in the Open-source world. Coders love to code, and explaining how best to use or improve the software tends to be deferred or even sidelined.

At Showmedo we believe the community can play a vital role here and also say thanks for the tools and software that make our lives easier. If you have a piece of software you love or a programming langugage you are enthusiastic about, why not make a screencast showing others how to use it? All the stuff you wish you'd been told, the tips, tricks, insights that would have saved you time and frustration.

Screencasting is easier than you think, and we're happy to help you. You can emailus for advice or just use some of the how-to screencasts on the site. This screencasting learning-pathis a good place to start.

Kudos and Thanks for Ian

Content

Feedback

Showmedo's development is fairly rapid and bugs will inevitably creep in. If you have any problems please drop us a line using the contact address below. Likewise, any suggestions for improvements to the site are gratefully received.

feedback@showmedo.com