1. #include <gtk/gtk.h> 
  2. //按钮的回调函数 
  3. void callback(GtkWidget *widget, gpointer  data) 
  4.     g_print("hello again-%s was presswd\n",(gchar *)data); 
  5.     //使用glib库的g_print在终端打印相应的字符 
  6. //关闭事件的回调函数 
  7. gint delete_event(GtkWidget *widget,GdkEvent *event,gpointer data) 
  8.     gtk_main_quit(); 
  9.     return FALSE; 
  10. int main(int argc , char *argv[]) 
  11.     GtkWidget *window; 
  12.     GtkWidget *button; 
  13.     GtkWidget *box1; 
  14.  
  15.     gtk_init(&argc,&argv); 
  16.     window = gtk_window_new(GTK_WINDOW_TOPLEVEL); 
  17.  
  18.     gtk_window_set_title(GTK_WINDOW(window),"pstary"); 
  19.      
  20.     g_signal_connect(G_OBJECT(window),"delete_event",G_CALLBACK(delete_event),NULL); 
  21.  
  22.     //设置窗口边框高度 
  23.     gtk_container_set_border_width(GTK_CONTAINER(window),30); 
  24.      
  25.     //创建一个组合框,看不见,只是作为排列构件的工具 
  26.     box1 = gtk_hbox_new(FALSE,0); 
  27.  
  28.     //将组合框加入到主窗口中 
  29.     gtk_container_add(GTK_CONTAINER(window),box1); 
  30.  
  31.     button = gtk_button_new_with_label("button 1"); 
  32.  
  33.     g_signal_connect(G_OBJECT(button),"clicked",G_CALLBACK(callback),"button 1"); 
  34.  
  35.     //将按钮加入到组合框中 
  36.     gtk_box_pack_start(GTK_BOX(box1),button,TRUE,TRUE,0); 
  37.  
  38.     //显示按钮 
  39.     gtk_widget_show(button); 
  40.  
  41.     button = gtk_button_new_with_label("button 2"); 
  42.  
  43.     g_signal_connect(G_OBJECT(button),"clicked",G_CALLBACK(callback),"button 2"); 
  44.  
  45.     gtk_box_pack_start(GTK_BOX(box1),button,TRUE,TRUE,0); 
  46.  
  47.     gtk_widget_show(button); 
  48.  
  49.     gtk_widget_show(box1); 
  50.  
  51.     gtk_widget_show(window); 
  52.  
  53.     gtk_main(); 
  54.  
  55.     return 0; 
  56.  

注意事件和信号回调函数的不同,运行结果如下:

GTK+信号和事件实例_信号回调

root@ubuntu:~/document/gtk# ./helloworld 

hello again-button 1 was presswd

hello again-button 1 was presswd

hello again-button 2 was presswd

hello again-button 2 was presswd

hello again-button 2 was presswd