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

Hi all, I know this is very basic question, but I am loosing my mind trying to solve it. Task is very simple, I am trying to create simple application to read data from serial port. The problem I have is Tk. I created nice window but I can not find out how to update textvariable for particular labels. Here is a simple example of code that should display current Unixtime, but does not, what is the problem??
#!/usr/bin/perl use warnings; use strict; use Tk; my $mw = new MainWindow; my $label = $mw -> Label(-textvariable =>\&timer); $label -> grid(-row=>1,-column=>1); $mw->repeat(1000,\&timer); MainLoop; sub timer{ my $time = time(); }

Replies are listed 'Best First'.
Re: Tk and textvariable update
by GrandFather (Saint) on Dec 19, 2011 at 01:13 UTC

    The main problem is that you aren't using a variable for -textvariable for the label. The code below fixes that and also passes a reference to the variable through to the sub that updates its contents:

    #!/usr/bin/perl use warnings; use strict; use Tk; my $mw = new MainWindow; my $time; my $label = $mw->Label(-textvariable => \$time); $label->grid(-row => 1, -column => 1); $mw->repeat(1000, sub {timer (\$time)}); MainLoop; sub timer { my ($varRef) = @_; $$varRef = time(); }
    True laziness is hard work
Re: Tk and textvariable update
by ~~David~~ (Hermit) on Dec 19, 2011 at 06:19 UTC
    Another way:
    #!/usr/bin/perl use warnings; use strict; use Tk; my $mw = new MainWindow; my $time = time(); my $label = $mw->Label(-textvariable => \$time); $label->grid(-row => 1, -column => 1); $mw->repeat(1000, sub{ $time = time(); } ); MainLoop;