Proper way to destroy a file chooser dialog in pygtk for python
Question: I've been trying to use gtk to create a folder choosing dialog, but I can't
figure out how to make the dialog close. Here is the code:

    
    
    from gi.repository import Gtk
    import time
    
    dialog = Gtk.FileChooserDialog("Please choose a folder", None,
    Gtk.FileChooserAction.SELECT_FOLDER,
        (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
        "Select", Gtk.ResponseType.OK))
    
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print("Select clicked")
        print("Folder selected: " + dialog.get_filename())
    elif response == Gtk.ResponseType.CANCEL:
        print("Cancel clicked")
    
    dialog.destroy()
    time.sleep(5)
    

I understand that I need to call gtk.main() in some way for it to work
properly, but I can't figure out how. I've been using the last example from
<http://python-gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html> but that
has a box at the beginning that I don't know how to get rid of.


Answer: There might be a nicer way, but I usually do it like this:

    
    
    from gi.repository import Gtk, Gdk, GLib
    
    def run_dialog(_None):
        dialog = Gtk.FileChooserDialog("Please choose a folder", None,
        Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
            "Select", Gtk.ResponseType.OK))
    
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Select clicked")
            print("Folder selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")
    
        dialog.destroy()
        Gtk.main_quit()
    
    
    Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
    Gtk.main()
    

This will call the `run_dialog` function as soon as the mainloop starts, which
will display the dialog and then quit.

**UPDATE:** If you want to enclose that code in a function that returns the
selected folder, you'll need to save the path to a non-local variable:

    
    
    def run_folder_chooser_dialog():
        result= []
    
        def run_dialog(_None):
            dialog = Gtk.FileChooserDialog("Please choose a folder", None,
            Gtk.FileChooserAction.SELECT_FOLDER,
                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                "Select", Gtk.ResponseType.OK))
    
            response = dialog.run()
            if response == Gtk.ResponseType.OK:
                result.append(dialog.get_filename())
            else:
                result.append(None)
    
            dialog.destroy()
            Gtk.main_quit()
    
    
        Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
        Gtk.main()
        return result[0]
    

In python 3, you can use `nonlocal result` and `result= dialog.get_filename()`
instead of the ugly list reference.

