【问题标题】:Creating array of buttons gtk in c在c中创建按钮数组gtk
【发布时间】:2016-04-22 01:32:47
【问题描述】:

我需要在 C 中创建按钮数组。我不确定我缺少什么,请帮助我。这是我的数组:

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:)

 /* 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++;

【问题讨论】:

  • 数组索引值以 0 开头。例如 for(i=0;i&lt;5;i++)
  • 好吧,想想当 i=5 时 i

标签: c arrays button widget gtk


【解决方案1】:

您的 for 循环以 1 的索引变量 (i) 开始,但是在计算机内存中,您声明的按钮数组的索引

GtkWidget *button[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 变量)(这就是 i++ 在 for(i = 0; i

【讨论】:

  • 我打错了,我的意思是 0。但是当你说 //do other things 时,其他的东西不应该也在循环中吗?
  • “做其他事情” eipi 只是意味着用按钮做任何你需要做的事情。要使用按钮,只需像使用普通标量按钮一样使用所需的数组成员。
  • 哎呀,我想我应该更清楚最后一点,谢谢 oldtechaa
猜你喜欢
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2010-11-17
  • 2014-09-19
  • 1970-01-01
  • 2020-09-11
  • 2016-08-15
相关资源
最近更新 更多