Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python GTK3: how to create a Gtk.FileChooseDialog?

Tags:

python

gtk3

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.

like image 594
Ricardo Magalhães Cruz Avatar asked Apr 30 '26 18:04

Ricardo Magalhães Cruz


1 Answers

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)
like image 82
zondo Avatar answered May 02 '26 08:05

zondo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!