Python GTK3: how to create a Gtk.FileChooseDialog?

2019-05-17 09:55发布

问题:

How to create a Gtk.FileChooseDialog properly?

This popular tutorial says to use code like the following:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

dialog = Gtk.FileChooserDialog("Please choose a folder", None,
    Gtk.FileChooserAction.SELECT_FOLDER,
    (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
     "Select", Gtk.ResponseType.OK))

But, if you run this with python -W error (to catch the deprecated warnings) it says:

  File "test3.py", line 8, in <module>
    "Select", Gtk.ResponseType.OK))
  File "/usr/lib/python2.7/dist-packages/gi/overrides/__init__.py", line 287, in new_init
    category, stacklevel=stacklevel)
gi.overrides.Gtk.PyGTKDeprecationWarning: Using positional arguments with the GObject constructor has been deprecated. Please specify keyword(s) for "title, parent, action, buttons" or use a class specific constructor. See: https://wiki.gnome.org/PyGObject/InitializerDeprecations

Using Gtk.FileChooserDialog.new gives TypeError: Dialog constructor cannot be used to create instances of a subclass FileChooserDialog.

The API says nothing about the constructor. Weird.

ps: The answer to this question should work with python -W error. It should not rely on deprecated APIs. It is the all point of me asking.

回答1:

Simply follow out the instructions and use keyword arguments. I also changed the buttons to using .add_buttons() since that also threw a DeprecationWarning:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

dialog = Gtk.FileChooserDialog(
    title="Please choose a folder",
    action=Gtk.FileChooserAction.SELECT_FOLDER,
)

dialog.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                   "Select", Gtk.ResponseType.OK)


标签: python gtk3