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

问题描述:

我已经完成了我的整个GUI定义,我在python 2.7中使用了PyGObject。我已经取得了一些小工具,有ID,我可以通过调用相应的ID,现在我一直在做这样的事情检索这些对象:我如何创建一个python类,它从Gtk构建器中获取它的定义

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文件的定义是一样的,因为这将是,它只是一个笔记本。我想要的是使课程本身成为笔记本,并预先载入我们在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> 

请注意,其笔记本只是一个基于您的小部件名称的随机示例,可能与其他小部件类型无关。