我需要在 C 中创建按钮数组。我不确定我缺少什么,请帮助我。这是我的数组:
GtkWidget *button[5];
int i;
for ( i =1; i<5; i++)
button[i] = gtk_button_new();
然后我创建其余的按钮...我使用 button [i]
然后最后我这样做 i++;
这可能不是最好的方式,但我只是不确定何时创建数组,如何在其余语句中传递按钮 1、按钮 2 等?
请任何帮助表示赞赏。
附注我是 C 语言新手,别对我太苛刻,ty:)
/* Creates a new button with the label "Button 1". */
button[i] = gtk_button_new_with_label ("Button 1");
/* Now when the button is clicked, we call the "callback" function
* with a pointer to "button 1" as its argiument */
g_signal_connect (button[i], "clicked",
G_CALLBACK (callback), "Run button 1");
/* Instead of gtk_container_add, we pack this button into the invisible
* box, which has been packed into the window. */
gtk_box_pack_start (GTK_BOX (box1), button[i], TRUE, TRUE, 0);
/* Always remember this step, this tells GTK that our preparation for
* this button is complete, and it can now be displayed. */
gtk_widget_show (button[i]);
i++;
最佳答案
您的 for 循环以索引变量 (i) 1 开始,但在计算机内存中,索引是您声明的按钮数组的索引
GtkWidget *按钮[5];
以索引 0 开始 (i = 0) 例如,您的代码应该类似于:
GtkWidget *button[5];
//not necessary since c99 can declare inside for() e.g for(int i = 0; i < 5; i++)
int i;
for(i = 0; i < 5; i++)
{
button[i] = gtk_button_new();
}
//do other stuff
然后要使用按钮,只需像访问常规数组一样访问它们即可,例如:
button[0] = gtk_button_new_with_label("button 1");
for 循环中不需要 i++,因为 for 循环在每次循环后自动递增迭代器(i 变量)(这就是 for(i = 0; i < 5; i++ 末尾的 i++ 的内容) )确实)
关于在c中创建按钮gtk数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36783214/