Home > OS >  Error Cannot create instance of abstract (non-instantiable) type `GtkBox' python3
Error Cannot create instance of abstract (non-instantiable) type `GtkBox' python3

Time:01-04

I have error when run this code:

from gi.repository import Gtk
class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="")
        # box
        self.box = Gtk.Box(spacing=10)
        self.add(self.box)
        # bacon button
        self.bacon_button = Gtk.Button(label="Bacon")
        self.bacon_button.connect("clicked", self.bacon_clicked)
        self.box.pack_start(self.bacon_button, True, True,0)
        # tuna button
        self.tuna_button = Gtk.Button(label="Tuna")
        self.tuna_button.connect("clicked", self.tuna_clicked)
        self.box.pack_start(self.tuna_button, True, True,0)
    def bacon_clicked(self, widget):
        print("You clicked Bacon")
    def tuna_clicked(self, widget):
        print("You clicked Tuna")

window = MainWindow()
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()

And error at output:

  File "/Users/*********/Documents/Program/Tutorial/venv/lib/python3.11/site-packages/gi/overrides/__init__.py", line 319, in new_init
    return super_init_func(self, **new_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot create instance of abstract (non-instantiable) type `GtkBox'
Process finished with exit code 1

I currently using python3 and already install PyGObject package in PyCharm

CodePudding user response:

Don't use Box directly. If you want a Box that grows horizontally with pack_start, use Gtk.HBox (documented here).

If you want it to grow vertically, use Gtk.VBox (documented here).

That being said, the more modern (GTK4) way of doing things is to use a Gtk.Grid for everything.

CodePudding user response:

Your code is loading GTK2, instead of GTK3; in GTK 2.x, GtkBox is indeed an abstract type.

If you want to use GTK 3.x, you will need to add:

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

at the top, before importing the Gtk namespace.

  • Related