How to hide a Gtk+ FileChooserDialog in Python 3.4?

天涯浪子 提交于 2019-12-07 04:51:38

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/29980352/how-to-hide-a-gtk-filechooserdialog-in-python-3-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!