Python脚本中的Gtk.main_quit()实际上并没有退出Gtk主循环

时间:2015-04-30 21:39:59

标签: python gtk

我有一个使用Gtk.FileChooserDialog对象的项目,显然允许用户选择文件。然后,一旦选择了文件,对话框就会消失,代码应该继续运行。

当对话框 消失时,代码不会在Gtk.main()之后继续 - 我的代码似乎卡在Gtk主循环中。

以下是代码:

from gi.repository import Gtk

class FileChooser(Gtk.FileChooserDialog):

        def __init__(self):

            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()
                dia.destroy()
                Gtk.main_quit() # <- Doesn't work?
            elif response == Gtk.ResponseType.CANCEL:
                print("Cancel clicked")
                dia.destroy()
                Gtk.main_quit() # <- Doesn't work?

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

            filter_text = Gtk.FileFilter()
            filter_text.set_name('Text files')
            filter_text.add_mime_type('text/plain')
            dia.add_filter(filter_text)

            filter_py = Gtk.FileFilter()
            filter_py.set_name('Python files')
            filter_py.add_mime_type('text/x-python')
            dia.add_filter(filter_py)

            filter_img = Gtk.FileFilter()
            filter_img.set_name('Image')
            filter_img.add_mime_type('image/*')
            dia.add_filter(filter_img)

dialog = FileChooser()
dialog.show_all()
Gtk.main()

在创建dialog.connect('destroy', Gtk.main_quit)对象后,我还尝试添加dia,但这也不起作用。

是否有一些明显的错误使得调用Gtk.main_quit()不会使我的代码退出Gtk主循环?

1 个答案:

答案 0 :(得分:2)

如果您只使用FileChooserDialog,则不必执行Gtk.main()Gtk.main_quit()。而且,Gtk.FileChooserDialog的继承是无用的,可以删除。

这应该有效:

from gi.repository import Gtk

class FileChooser():

        def __init__(self):

            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):
            pass  # filters left out to make the snippet shorter

dialog = FileChooser()