Thursday, August 14, 2008

gtk.FileChooserDialog() mini-HOWTO

Enough is enough! It seems like every time I write a pygtk app I end up needing a file chooser dialog yet every time I can't remember the details. The reference page for gtk.FileChooserDialog() is excellent--for reference. I need a gtk.FileChooserDialog() mini-HOWTO. Here it is:

fc = gtk.FileChooserDialog(title='Open File...',
                                   parent=None,
                                   action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                   buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        fc.set_current_folder(g_directory)
        fc.set_default_response(gtk.RESPONSE_OK)
        filter = gtk.FileFilter()
        filter.set_name('Audio Files')
        filter.add_pattern('*.wav')
        filter.add_pattern('*.mp3')
        filter.add_pattern('*.flac')
        fc.add_filter(filter)
        response = fc.run()
        if response == gtk.RESPONSE_OK:
            print 'ok'
            print fc.get_filename()
            self.entry.set_text(fc.get_filename())
            g_directory = fc.get_current_folder()
        else:
            print 'not ok'
        fc.destroy()
There, done! This page is also an excellent, more complete, example.