- #include <gtk/gtk.h>
- //按钮的回调函数
- void callback(GtkWidget *widget, gpointer data)
- {
- g_print("hello again-%s was presswd\n",(gchar *)data);
- //使用glib库的g_print在终端打印相应的字符
- }
- //关闭事件的回调函数
- gint delete_event(GtkWidget *widget,GdkEvent *event,gpointer data)
- {
- gtk_main_quit();
- return FALSE;
- }
- int main(int argc , char *argv[])
- {
- GtkWidget *window;
- GtkWidget *button;
- GtkWidget *box1;
- gtk_init(&argc,&argv);
- window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
- gtk_window_set_title(GTK_WINDOW(window),"pstary");
- g_signal_connect(G_OBJECT(window),"delete_event",G_CALLBACK(delete_event),NULL);
- //设置窗口边框高度
- gtk_container_set_border_width(GTK_CONTAINER(window),30);
- //创建一个组合框,看不见,只是作为排列构件的工具
- box1 = gtk_hbox_new(FALSE,0);
- //将组合框加入到主窗口中
- gtk_container_add(GTK_CONTAINER(window),box1);
- button = gtk_button_new_with_label("button 1");
- g_signal_connect(G_OBJECT(button),"clicked",G_CALLBACK(callback),"button 1");
- //将按钮加入到组合框中
- gtk_box_pack_start(GTK_BOX(box1),button,TRUE,TRUE,0);
- //显示按钮
- gtk_widget_show(button);
- button = gtk_button_new_with_label("button 2");
- g_signal_connect(G_OBJECT(button),"clicked",G_CALLBACK(callback),"button 2");
- gtk_box_pack_start(GTK_BOX(box1),button,TRUE,TRUE,0);
- gtk_widget_show(button);
- gtk_widget_show(box1);
- gtk_widget_show(window);
- gtk_main();
- return 0;
- }
注意事件和信号回调函数的不同,运行结果如下:
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