我如何创建一个 python class 从 Gtk 构建器获取它的定义

How I can create a python class that takes it definition from Gtk builder

我已经在 glade 上完成了整个 GUI 定义,我正在使用 PyGObject 和 python 2.7。我制作了一些具有 id 的小部件,我可以通过调用相应的 id 来检索这些对象,现在我一直在做这样的事情:

class MLPNotebookTab:
    def __init__(self):
        builder = Gtk.Builder.new_from_file(UI_FILE)
        builder.connect_signals(self)
        self.notebook = builder.get_object('MLPNotebook')

    def add_tab(self, content):
        pages = self.notebook.get_n_pages()
        label = "MLP #" + str(pages + 1)
        tab = NotebookTabLabel(label, self.notebook, pages + 1)
        self.notebook.append_page(content, tab.header)

    def on_btn_add_tab_clicked(self, button):
        self.add_tab(Gtk.Label(label= "test"))

ui文件的定义和原来一样,只是一个笔记本。我想要的是使 class 成为笔记本本身并预加载我们在 ui 文件中设置的其他属性。我在这里找到了某种实现方式:https://eeperry.wordpress.com/2013/01/05/pygtk-new-style-python-class-using-builder/

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gtk, sys, os

class MainWindow(gtk.Window):
    __gtype_name__ = "MainWindow"

    def __new__(cls):
        """This method creates and binds the builder window to class.

        In order for this to work correctly, the class of the main
        window in the Glade UI file must be the same as the name of
        this class."""
        app_path = os.path.dirname(__file__)
        try:
            builder = gtk.Builder()
            builder.add_from_file(os.path.join(app_path, "main.ui"))
        except:
            print "Failed to load XML GUI file main.ui"
            sys.exit(1)
        new_object = builder.get_object('window')
        new_object.finish_initializing(builder)
        return new_object

    def finish_initializing(self, builder):
        """Treat this as the __init__() method.

        Arguments pass in must be passed from __new__()."""
        builder.connect_signals(self)

        # Add any other initialization here

我不知道这是否是最好的方法。请帮忙!

您可以使用这个第三方库(只需复制到树中):https://github.com/virtuald/pygi-composite-templates

它看起来像这样:

from gi.repository import Gtk
from gi_composites import GtkTemplate

PATH_TO_UI_FILE='foo'

@GtkTemplate(ui=PATH_TO_UI_FILE)
class MLPNotebook(Gtk.Notebook):
    __gtype_name__ = 'MLPNotebook'

    def __init__(self):
        Gtk.Notebook.__init__(self)
        self.init_template()

您的 UI 文件包含模板小部件:

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <template class="MLPNotebook" parent="GtkNotebook">
    <!-- Stuff goes here -->
  </template>
</interface>

请注意,它的笔记本只是一个基于您的小部件名称的随机示例,与另一种小部件类型相比可能没有意义。