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

I'm trying to get the hang of perl Tk. I thought an extreamly simple clock would be a good project. Getting the time is easy enough, as is displaying it. But what I want is a label that updates every second.

Anyway I went through the tk documentation, but it is very short on code examples, I tried to used the Tk::After method, but I didn't do anything new, I just get a window with a static time. I couldn't find anything I could use when I did a super search. Can someone point me in the right direction?

My project so far:

#!/usr/bin/perl use Tk; $top = new MainWindow; $id = Tk::After->new($top->Label(-text =>&gettime)->pack,1000,'rep +eat',\&gettime); MainLoop; sub gettime{ ($sec,$min,$hour,$day,$month,$year,$wday,$yday,$isDST) = localtime +(); @mname=("January","February","March","April","May","June", "July","August","September","October","November","December +"); @weekday=("Sunday","Monday","Tuesday","Wednesday","Thursday","Frid +ay","Saturday"); for($sec,$min){$_="0$_"if($_<10);} $dst = $isDST?"Daylight Savings Time":"Standard Time"; $year = $year +1900; $timestring= "$weekday[$wday] $mname[$month] $day," . $year . " $h +our:$min:$sec$x\n"; }

Replies are listed 'Best First'.
Re: Refresh Display in Perl Tk
by danger (Priest) on Nov 04, 2001 at 01:19 UTC

    If you use the '-textvariable' option (instead of '-text'), you can update the variable and the widget will also update. Also, instead of calling Tk::After, use the 'repeat' method on the Label widget itself. Here is one way (I've replaced your gettime() function with a simple call to localtime() in scalar context to make the date string):

    #!/usr/bin/perl -w use strict; use Tk; my $top = new MainWindow; my $text = localtime(); my $id = $top->Label(-textvariable => \$text)->pack; $id->repeat(1000,sub{$text = localtime()}); MainLoop; __END__
      danger, that did it. I just replaced your call to localtime, with my &gettime sub. It works great now, my sub returns the last thing evaluated(the string $timestring)
      Thanks for the help, all!
Re: Refresh Display in Perl Tk
by BigJoe (Curate) on Nov 04, 2001 at 01:04 UTC
    I think you need to actually change the text in the label. This should make it refresh. I would suggest looking at this. When I did VB applications this is what we had to do so I think it would be the same for Perl. This has not been tested and it is just my weekend ramblings.
    #!/usr/bin/perl use strict; use Tk; my $top = new MainWindow; my $not_stopped = 1; my $id = ""; while($not_stopped){ $id = $top->Label(-text =>&gettime); sleep(10); }


    --BigJoe

    Learn patience, you must.
    Young PerlMonk, craves Not these things.
    Use the source Luke.