如何在 Python 3.4 中隐藏 Gtk+ FileChooserDialog?

How to hide a Gtk+ FileChooserDialog in Python 3.4?

我设置了一个程序,它可以单独显示一个 FileChooserDialog(没有主 Gtk window,只有对话框)。

我遇到的问题是对话框没有消失,即使在用户选择了文件并且程序似乎继续执行之后也是如此。

下面是展示此问题的片段:

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()

该对话框仅在程序以 quit() 函数调用退出时消失。

我也尝试过 dia.hide(),但这也不起作用 - 在代码继续时对话框仍然可见 运行。

使对话框消失的正确方法是什么?

编辑:从那以后,我了解到不鼓励在没有父项的情况下制作 Gtk 对话框 window。但是,我不想处理必须让用户关闭一个 window 的问题,它里面什么都没有,只是作为对话框的父级。

有没有办法让父对象不可见window,然后在对话框消失时退出 Gtk 主循环?

您可以先设置一个 window,方法是:

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))

此外,为路径设置一个默认值以防用户取消:

  path = ''

然后,在您的脚本末尾:

print (path)

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

print ("done")

收集并处理所有events