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

我有一个程序设置,以便它自己显示FileChooserDialog(没有主Gtk窗口,只有对话框)。

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.

当程序退出并使用quit()函数调用时,该对话框才会消失。

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

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

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.

编辑:我已经知道在没有父窗口的情况下制作Gtk对话框是不鼓励的。但是,我不想处理必须让用户关闭一个没有任何内容的窗口,只是作为对话框的父窗口。

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

是否有办法制作一个不可见的父窗口,然后在对话框消失时退出Gtk主循环?

1 个解决方案

#1


5  

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.

收集和处理所有事件。

智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告