glade 与 gtk
GTK+ and Glade3 GUI Programming Tutorial
知识点
glade3与glade2差别
glade2生成代码,而glade3只生成xml文件(实现了与代码分离,支持其他语言调用,如python)
如何运行glade3生成的xml界面
借助libglade库读取xml文件,并生成控件
示例
test.glade
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> <!--Generated with glade3 3.4.0 on Tue Nov 20 14:05:37 2007 --> <glade-interface> <widget class="GtkWindow" id="window1"> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <placeholder/> </child> </widget> </glade-interface>
在test.glade的同级目录下,编写源码main.c
#include <gtk/gtk.h> #include <glade/glade.h> int main(int argc, char **argv) { GladeXML *gxml; GtkWidget *window; gtk_init(&argc, &argv); gxml = glade_xml_new("test.glade", NULL, NULL); // 读取xml文件 window = glade_xml_get_widget(gxml, "window1"); // 获取名为window1控件的指针 g_object_unref(G_OBJECT(gxml)); gtk_widget_realize(window); gtk_widget_show(window); gtk_main(); return 0; }
编译
gcc main.c -o main `pkg-config --libs --cflags gtk+-2.0 libglade-2.0`
执行结果
./main
显示gtk建立的窗口
自 gtk 的版本升到 2.12,它就包含了 GtkBuilder .(pkg-config --modversion gtk+-2.0 查看版本)
GtkBuilder 的作用和 libglade 一样,用来加载 glade 文件,
所以,如果使用 GtkBuilder 来代替 libglade ,这样就可以在使用过程中,减少一个依赖
main.c
/* First run tutorial.glade through gtk-builder-convert with this command: gtk-builder-convert tutorial.glade tutorial.xml Then save this file as main.c and compile it using this command (those are backticks, not single quotes): gcc -Wall -g -o main main.c `pkg-config --cflags --libs gtk+-2.0` -export-dynamic Then execute it using: ./tutorial */ #include <gtk/gtk.h> void on_window_destroy (GtkObject *object, gpointer user_data) { gtk_main_quit (); } int main (int argc, char *argv[]) { GtkBuilder *builder; GtkWidget *window; gtk_init (&argc, &argv); builder = gtk_builder_new (); gtk_builder_add_from_file (builder, "test.glade", NULL); window = GTK_WIDGET (gtk_builder_get_object (builder, "window1")); gtk_builder_connect_signals (builder, NULL); g_object_unref (G_OBJECT (builder)); gtk_widget_show (window); gtk_main (); return 0; }
使用python调用xml
test.py
import gtk import gtk.glade def some_handler(widget): pass xml = gtk.glade.XML('test.glade') widget = xml.get_widget('window1') xml.autoconnect({ 'some_handler': some_handler }) gtk.main()
完