源代码如下:
#include<gtk/gtk.h> #include<stdio.h> #include<stdlib.h> GtkWidget *name;//定义一个全局变量 GtkWidget *pass; char id1[]="oyx1";//自行定义用户1和用户2 char id2[]="oyx2"; char pw1[]="oyx1"; char pw2[]="oyx2"; void callback(GtkWidget *widget,gpointer data){ const char* username;//字符型指针常量用来存地址 const char* password; username=(gchar *)malloc(sizeof(gchar));//分配好地址空间存储获取的文本 password=(gchar *)malloc(sizeof(gchar)); while(1){ username=gtk_entry_get_text(GTK_ENTRY(name));//通过输入框获取函数获取文本 password=gtk_entry_get_text(GTK_ENTRY(pass)); if(strcmp(id1,username)==0&&strcmp(pw1,password)==0){ //以获取的文本标志位做条件判断 g_print("登入成功"); break; } else if(strcmp(id2,username)==0&&strcmp(pw2,password)==0){ g_print("登入成功"); break; } else{ g_print("登入失败,请重新输入!"); break; } } gtk_main_quit(); //终止程序 } int main(int argc,char *argv[]){ GtkWidget *window; GtkWidget *button; GtkWidget *label1; GtkWidget *label2; GtkWidget *hbox1; GtkWidget *hbox2; GtkWidget *vbox1; GtkWidget *vbox2; GtkWidget *vbox3; char *title="火车站出租车拉客系统"; gtk_init(&argc,&argv);//通过地址找到好的参数为后续做准备 window=gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window),"delete_event",G_CALLBACK(gtk_main_quit),NULL); label1=gtk_label_new("用户名:"); label2=gtk_label_new("密码:"); vbox1=gtk_vbox_new(FALSE,0); vbox2=gtk_vbox_new(FALSE,10); vbox3=gtk_vbox_new(FALSE,10); hbox1=gtk_hbox_new(FALSE,0); hbox2=gtk_hbox_new(TRUE,0); button=gtk_button_new_with_label("登入"); gtk_window_set_title(GTK_WINDOW(window),title); gtk_widget_set_size_request(window,500,450); //设置窗口的大小 gtk_container_set_border_width(GTK_CONTAINER(window),10); gtk_container_add(GTK_CONTAINER(window),vbox1); gtk_box_pack_start(GTK_BOX(vbox2),label1,TRUE,FALSE,0); gtk_widget_show(label1); gtk_box_pack_start(GTK_BOX(vbox2),label2,TRUE,FALSE,0); gtk_widget_show(label2); gtk_box_pack_start(GTK_BOX(hbox1),vbox2,TRUE,FALSE,0); gtk_widget_show(vbox2); name=gtk_entry_new(); gtk_entry_set_visibility(GTK_ENTRY(name),TRUE); pass=gtk_entry_new(); gtk_entry_set_visibility(GTK_ENTRY(pass),FALSE); gtk_box_pack_start(GTK_BOX(vbox3),name,TRUE,FALSE,0); gtk_widget_show(name); gtk_box_pack_start(GTK_BOX(vbox3),pass,TRUE,FALSE,0); gtk_widget_show(pass); gtk_box_pack_start(GTK_BOX(hbox1),vbox3,TRUE,FALSE,0); gtk_widget_show(vbox3); gtk_box_pack_start(GTK_BOX(vbox1),hbox1,TRUE,FALSE,0); gtk_widget_show(hbox1); button=gtk_button_new_with_label("登入"); g_signal_connect(G_OBJECT(button),"clicked",G_CALLBACK(callback),NULL); gtk_box_pack_start(GTK_BOX(hbox2),button,TRUE,TRUE,0); gtk_widget_show(button); gtk_box_pack_start(GTK_BOX(vbox1),hbox2,TRUE,FALSE,0); gtk_widget_show(hbox2); gtk_widget_show(vbox1); gtk_widget_show_all(window); //展示所以的构件 gtk_main(); return 0; }
以上注意几点:
1.通过代码name=gtk_entry_new();//可以得到输入框
2.通过gtk_entry_set_visibility(GTK_ENTRY(name),TRUE);设置输入框文本可见
通过gtk_entry_set_visibility(GTK_ENTRY(pass),FALSE);设置输入框文本不可见
3.可以通过username=gtk_entry_get_text(GTK_ENTRY(name));
password=gtk_entry_get_text(GTK_ENTRY(pass));
获取到输入框的文本内容
正是步行者,一步步登峰!