虽然,GTK+的入门程序已经看过很多次了,但是,我还是坚持着把示例代码敲了一遍,只为更加熟悉这些函数,以及GTK+程序的结构。
参看awaysoft.com/gtk2-tut2/ 进行练习。
今天看了前面两个。
Makefile文件现在还是不会,所以,我就写了个一行的shell来进行编译,毕竟敲打gcc -o simple simple.c `pkg-config –libs –flags gtk+-2.0`是很不方便的,这里我建立了一个compile文件,内容就是gcc -o simple simple.c `pkg-config –libs –flags gtk+-2.0`,然后用chmod赋予了执行权限
一次次的跟着教程对代码进行修改,最后的结果:
/* * ===================================================================================== * * Filename: simple.c * * Description: Simple GTK+ * * Version: 1.0 * Created: 2010年04月21日 00时10分22秒 * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Company: * * ===================================================================================== */ #include gint count = 0; char buf[5]; void increase(GtkWidget *widget,gpointer label) { count++; sprintf(buf,"%d",count); gtk_label_set_text(label,buf); } void decrease(GtkWidget *widget,gpointer label) { count--; sprintf(buf,"%d",count); gtk_label_set_text(label,buf); } int main(int argc,char *argv[]) { GtkWidget *window; GtkWidget *label; GtkWidget *frame; GtkWidget *plus; GtkWidget *minus; gtk_init(&argc,&argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window),"Simple GTK+"); gtk_window_set_default_size(GTK_WINDOW(window),230,180); gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); frame = gtk_fixed_new(); gtk_container_add(GTK_CONTAINER(window),frame); plus = gtk_button_new_with_label("+"); gtk_widget_set_size_request(plus,80,35); gtk_fixed_put(GTK_FIXED(frame),plus,50,20); minus = gtk_button_new_with_label("-"); gtk_widget_set_size_request(minus,80,35); gtk_fixed_put(GTK_FIXED(frame),minus,50,80); label = gtk_label_new("0"); gtk_fixed_put(GTK_FIXED(frame),label,190,58); gtk_widget_show_all(window); g_signal_connect(G_OBJECT(window),"destroy", G_CALLBACK(gtk_main_quit),NULL); g_signal_connect(plus,"clicked", G_CALLBACK(increase),label); g_signal_connect(minus,"clicked", G_CALLBACK(decrease),label); gtk_main(); return 0; }
总结:在写GTK+程序中,gtk_init(&argc,&argv);gtk_main();这两句是必不可少的,一个函数是初始化gtk的环境,一个是主循环,而这两个函数中间就是放置控件,绑定事件,信号等等,写一个简单的GTK+程序,还是很简单的。