RPiAwesomeness
RPiAwesomeness

Reputation: 5159

How to hide a Gtk+ FileChooserDialog in Python 3.4?

I have a program set up so that it displays a FileChooserDialog all by itself (no main Gtk window, just the dialog).

The problem I'm having is that the dialog doesn't disappear, even after the user has selected the file and the program has seemingly continued executing.

Here's a snippet that showcases this issue:

from gi.repository import Gtk

class FileChooser():

    def __init__(self):

        global path

        dia = Gtk.FileChooserDialog("Please choose a file", None,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        self.add_filters(dia)

        response = dia.run()

        if response == Gtk.ResponseType.OK:
            print("Open clicked")
            print("File selected: " + dia.get_filename())
            path = dia.get_filename()
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dia.destroy()

    def add_filters(self, dia):
        filter_any = Gtk.FileFilter()
        filter_any.set_name("Any files")
        filter_any.add_pattern("*")
        dia.add_filter(filter_any)

dialog = FileChooser()

print(path)

input()
quit()

The dialog only disappears when the program exits with the quit() function call.

I've also tried dia.hide(), but that doesn't work either - the dialog is still visible while code continues running.

What would the proper way to make the dialog disappear?

EDIT: I've since learned that it's discouraged to make a Gtk dialog without a parent window. However, I don't want to deal with having to have the user close a window that has nothing in it and simply stands as the parent for the dialog.

Is there a way to make an invisible parent window and then quit the Gtk main loop when the dialog disappears?

Upvotes: 5

Views: 652

Answers (1)

gauteh
gauteh

Reputation: 17195

You can set up a window first by doing:

def __init__ (self):

  [.. snip ..]

  w = Gtk.Window ()

  dia = Gtk.FileChooserDialog("Please choose a file", w,
        Gtk.FileChooserAction.OPEN,
        (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
         Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

also, set a default value for path in case the user cancels:

  path = ''

Then, at the end of your script:

print (path)

while Gtk.events_pending ():
  Gtk.main_iteration ()

print ("done")

to collect and handle all events.

Upvotes: 6

Related Questions