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

I'd like to create a simple (and I do mean *simple*) button counter, kinda like those hand-held clickers that advance by one.

After pressing the button, I'm refreshing the window, but this doesn't seem to yield the desired result of showing the new value. It's probably something obvious, but it's lost on me. This code isn't elegant like some I've seen here, but this is the gist:

use Tk; use warnings; use strict; my $count = 0; my $mw = MainWindow -> new; $mw -> Label(-text => 'Counter') ->pack(); $mw -> Label(-text => $count ) ->pack(); $mw -> Button( -text => 'Count', -command => sub { $count++; $mw -> + update; } ) ->pack(); MainLoop;

Replies are listed 'Best First'.
Re: simple tk counter
by tybalt89 (Monsignor) on May 31, 2017 at 13:34 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1191710 use strict; use warnings; use Tk; my $count = 0; my $mw = MainWindow -> new; $mw -> Label(-text => 'Counter') ->pack(); $mw -> Label(-textvariable => \$count ) ->pack(); $mw -> Button( -text => 'Count', -command => sub { $count++ } ) ->p +ack(); MainLoop;

      Yeah, the use of -textvariableworked perfectly. Thank you tybalt89!

Re: simple tk counter
by 1nickt (Canon) on May 31, 2017 at 13:35 UTC

    After pressing the button, I'm refreshing the window, but this doesn't seem to yield the desired result of showing the new value

    Hi, I don't use Tk at all, but, maybe try:

    $mw -> Button( -text => 'Count', -command => sub { ++$count; $mw -> + update; } ) ->pack();
    ... which will increment the value of $count before using it, instead of after.

    Hope this helps!


    The way forward always starts with a minimal test.