使用Glade来进行GTK开发效率比较高,下面是一个例子。
将以下代码保存为test.glade文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| <?xml version="1.0" encoding="UTF-8"?> <interface> <requires lib="gtk+" version="2.24"/> <object class="GtkWindow" id="window1"> <property name="can_focus">False</property> <property name="resizable">False</property> <property name="default_width">440</property> <property name="default_height">450</property> <signal name="destroy" handler="on_MainWindow_destroy" swapped="no"/> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="top_padding">10</property> <property name="bottom_padding">10</property> <property name="left_padding">10</property> <property name="right_padding">10</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">龙昌博客: http://www.xefan.com</property> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="button1"> <property name="label" translatable="yes">关闭</property> <property name="use_action_appearance">False</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_MainWindow_destroy" swapped="no"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> </object> </interface>
|
将以下代码保存为test.py文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
try: import pygtk pygtk.require("2.0") except: pass try: import gtk import gtk.glade except: exit(1)
class GBuilder: def delete_event(self,widget,event,data=None): return gtk.FALSE def on_MainWindow_destroy(self,widget,data=None): gtk.main_quit() def __init__(self): builder = gtk.Builder() builder.add_from_file("test.glade") builder.connect_signals(self)
self.button1 = builder.get_object("button1") self.window = builder.get_object("window1") self.window.show()
if __name__ == "__main__": window=GBuilder() gtk.main()
|
然后运行查看效果。