Python3实例化GtkBox报错:无法创建抽象类型实例
解决GtkBox实例化报错问题
我运行以下Python代码时出现错误:
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()
报错内容如下:
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
我当前使用Python3,且已在PyCharm中安装PyGObject包。
问题原因
GtkBox是抽象类,无法直接实例化,必须使用它的具体构造方式或子类。
修复方案
将创建Box的代码从self.box = Gtk.Box(spacing=10)替换为Gtk.Box.new()方法,同时指定布局方向参数:
修复后的完整代码
from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="") # 使用Box.new()实例化,指定水平布局方向 self.box = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, 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()
补充说明
- 在GTK 3及以上版本中,
GtkBox作为抽象基类,必须通过new()方法创建实例,需传入orientation参数(可选Gtk.Orientation.HORIZONTAL水平布局或Gtk.Orientation.VERTICAL垂直布局)。 - 若需要垂直排列控件,将
orientation参数替换为Gtk.Orientation.VERTICAL即可。
内容的提问来源于stack exchange,提问作者fandi
相关产品推荐
相关产品推荐

