在c中创建按钮数组gtk [英] Creating array of buttons gtk in c
问题描述
我需要在 C 中创建按钮数组.我不确定我缺少什么,请帮助我.这是我的数组:
I need to create array of buttons in C. I am not sure what am I missing, please help me. Here is my array:
GtkWidget *button[5];
int i;
for ( i =1; i<5; i++)
button[i] = gtk_button_new();
然后我创建其余的按钮...我正在使用 button [i]
然后最后我这样做 i++;
这可能不是最好的方式,但我只是不确定当我创建数组时,如何在我的其余语句中传递按钮 1、按钮 2 等?请任何帮助表示赞赏.p.s.我是 C 新手,不要对我苛刻,ty:)
Then I creating the rest of the buttons... I am using button [i]
and then at the end i do this i++;
This probably not the best way, but i am just not sure when I create the array, how do I pass button 1, button 2 and etc in the rest of my statements?
Please any help appreciated.
p.s. I am new in C, dont be harsh on me, 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 开始,但是在计算机内存中,您声明的按钮数组的索引
your for loop starts with an index variable (i) of 1 however in the computer's memory the index to the array of buttons that you declared with
GtkWidget *button[5];
GtkWidget *button[5];
从索引 0 (i = 0) 开始因此,例如,您的代码应类似于:
starts with an index of 0 (i = 0) so for example your code should look something like:
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
然后要使用按钮,只需像访问常规数组一样访问它们,例如:
then to use the buttons just access them like you would a regular array eg:
button[0] = gtk_button_new_with_label("button 1");
你不需要在 for 循环中使用 i++,因为 for 循环会在每次循环后自动递增迭代器(i 变量)(这就是 for(i = 0; i < 5; 末尾的 i++)i++) 确实)
you do not need the i++ inside of the for loop because the for loop automatically increments the iterator (i variable) after every loop (this is what the i++ at the end of for(i = 0; i < 5; i++) does)
这篇关于在c中创建按钮数组gtk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!