我正在尝试为按钮实现数组,而不是声明
GtkWidget *button1;
GtkWidget *button2;
如果我有更多按钮。这是我的代码,它运行没有错误。我不确定如何实现数组,因为对于每个按钮我还需要一个新的标签名称...并在此处添加另一条数据g_signal_connect
...
这是我的代码:
#include <gtk/gtk.h>
/* Our new improved callback. The data passed to this function
* is printed to stdout. */
static void callback (GtkWidget *widget, gpointer data)
{
system ((gchar *) data);
}
/* another callback */
static gboolean delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
{
gtk_main_quit ();
return FALSE;
}
int main (int argc, char *argv[])
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window;
GtkWidget *button1;
GtkWidget *button2;
GtkWidget *box1;
/* This is called in all GTK applications. Arguments are parsed
* from the command line and are returned to the application. */
gtk_init (&argc, &argv);
/* Create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
/* This is a new call, which just sets the title of our
* new window to "My Assignments" */
gtk_window_set_title (GTK_WINDOW (window), "My Assignments");
/* Here we just set a handler for delete_event that immediately
* exits GTK. */
g_signal_connect (window, "delete-event",
G_CALLBACK (delete_event), NULL);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 50);
/* We create a box to pack widgets into. This is described in detail
* in the "packing" section. The box is not really visible, it
* is just used as a tool to arrange widgets. */
box1 = gtk_vbox_new (FALSE,0);
/* Put the box into the main window. */
gtk_container_add (GTK_CONTAINER (window), box1);
/*creating 1st button*/
button1 = gtk_button_new_with_label ("Run program1");
g_signal_connect (button1, "clicked",
G_CALLBACK (callback), "program1");
gtk_box_pack_start (GTK_BOX (box1), button1, TRUE, TRUE, 0);
gtk_widget_show(button1);
/*creating 2nd button*/
button2 = gtk_button_new_with_label ("Run program2");
g_signal_connect (button2, "clicked",
G_CALLBACK (callback), "program2");
gtk_box_pack_start (GTK_BOX (box1), button2, TRUE, TRUE, 0);
gtk_widget_show(button2);
gtk_widget_show (box1);
/* Rest in gtk_main and wait for the fun to begin! */
gtk_main ();
return 0;
}
答案 0 :(得分:2)
只需使用:
GtkWidget* button[NB_BUTTONS];
然后
int i;
for (i = 0: i < NB_BUTTONS; i++)
{
char lab[16];
char prg[16];
sprintf(lab, "Run program%d", i);
sprintf(prg, "program%d", i);
button[i] = gtk_button_new_with_label (lab);
g_signal_connect (button[i], "clicked",
G_CALLBACK (callback), prg);
}
你也可以定义你的标签&amp; prgram以这种方式命名:
char* label[] = {"Run program1", "Run whatever2" /*, ...*/ };
char* progs[] = {"program1", "whatever2" /*, ...*/ };
int i;
for (i = 0: i < NB_BUTTONS; i++)
{
button[i] = gtk_button_new_with_label (label[i]);
g_signal_connect (button[i], "clicked",
G_CALLBACK (callback), progs[i]);
}