2017-08-07 3 views
0

glade全体のGUI定義全体を作成しましたが、私はPython 2.7でPyGObjectを使用しています。 、Gtkビルダーから定義を取得するPythonクラスを作成する方法

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ファイルの定義は、それがだろうとちょうど同じである:私はIDを持っているいくつかのウィジェットを作っていると私は今、私はこのような何かをやってきたために、対応するIDを呼び出すことによって、それらのオブジェクトを取得することができますそれは単なるノートブックです。私が望むのは、クラスをノートブック自体にして、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 

それはそれを行うための最善の方法だ場合、私は知りません。助けてください!

答えて

0

あなたはこのサードパーティのライブラリ(ちょうどツリーにコピー)を使用することができます:https://github.com/virtuald/pygi-composite-templates

をそして、それは次のようになります。

<?xml version="1.0" encoding="UTF-8"?> 
<interface> 
    <template class="MLPNotebook" parent="GtkNotebook"> 
    <!-- Stuff goes here --> 
    </template> 
</interface> 
:テンプレートウィジェットを含むあなたのUIファイルで

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() 

ノートブックは、あなたのウィジェット名に基づいた単なるランダムな例であったことに注意してください。これはおそらく意味をなさないでしょう。別のウィジェットタイプです。

関連する問題