Muskovitz has asked for the wisdom of the Perl Monks concerning the following question:

hello monks i was trying to use for loops in perl gtk2 heres my very simple code
#!/usr/bin/perl use strict; use warnings; use Glib qw/TRUE FALSE/; use Gtk2 '-init'; my $window=Gtk2::Window->new(); $window->signal_connect('delete_event',sub{Gtk2::main_quit;}); my $num=0; my $vbox1=Gtk2::VBox->new; my $label=Gtk2::Label->new("Total Count: $num"); for (1 .. 5){ $num=$_; $label->set_text("Total Count: $num"); } $vbox1->add($label); $window->add($vbox1); $window->show_all; Gtk2->main; </pre>
i was expecting the result would be
->Expectation<- Total Count: 1 Total Count: 2 Total Count: 3 Total Count: 4 Total Count: 5 ->Result<- Total Count: 5
i was expecting to loop from 1 to 5 but it only prints 5 is there something wrong with my code but i guess the error is in the packing method like `->pack` in perl/Tk

Replies are listed 'Best First'.
Re: trying to use loops in perl gtk2
by Corion (Patriarch) on Jan 05, 2015 at 13:37 UTC

    You only create one $label outside of the loop. If you want to create five labels, you need to put the label creation into the loop:

    ... my $vbox1=Gtk2::VBox->new; for my $num (1 .. 5){ my $label=Gtk2::Label->new("Total Count: $num"); $vbox1->add($label); } $window->add($vbox1);
      thanks `Corion` thats what i need, very thanks! but i think
      my $num=0;
      is just a waste code! btw thanks again!