in reply to A timer in Tcl/Tk in Perl::Tk

See How to implement a timer in perl?, and ......
#!/usr/bin/perl -w # # This script generates a counter with start and stop buttons. Exit w +ith # Ctrl/c or Ctrl/q. # # This a more advanced version of `timer', where we conform to a stric +t style # of Perl programming and thus use lexicals. Also, the counter is upd +ated via # a -textvariable rather than a configure() method call. # # Tcl/Tk -> Perl translation by Stephen O. Lidie. lusol@Lehigh.EDU 9 +6/01/25 require 5.002; use Tk; use strict; sub tick; my $MW = MainWindow->new; $MW->bind('<Control-c>' => \&exit); $MW->bind('<Control-q>' => \&exit); # %tinfo: the Timer Information hash. # # Key Contents # # w Reference to MainWindow. # s Accumulated seconds. # h Accumulated hundredths of a second. # p 1 IIF paused. # t Value of $counter -textvariable. my(%tinfo) = ('w' => $MW, 's' => 0, 'h' => 0, 'p' => 1, 't' => '0.00') +; my $start = $MW->Button( -text => 'Start', -command => sub {if($tinfo{'p'}) {$tinfo{'p'} = 0; tick}}, ); my $stop = $MW->Button(-text => 'Stop', -command => sub {$tinfo{'p'} = + 1;}); my $counter = $MW->Label( -relief => 'raised', -width => 10, -textvariable => \$tinfo{'t'}, ); $counter->pack(-side => 'bottom', -fill => 'both'); $start->pack(-side => 'left', -fill => 'both', -expand => 'yes'); $stop->pack(-side => 'right', -fill => 'both', -expand => 'yes'); sub tick { # Update the counter every 50 milliseconds, or 5 hundredths of a s +econd. return if $tinfo{'p'}; $tinfo{'h'} += 5; if ($tinfo{'h'} >= 100) { $tinfo{'h'} = 0; $tinfo{'s'}++; } $tinfo{'t'} = sprintf("%d.%02d", $tinfo{'s'}, $tinfo{'h'}); $tinfo{'w'}->after(50, \&tick); } # end tick MainLoop;

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku ................... flash japh

Replies are listed 'Best First'.
Re^2: A timer in Tcl/Tk in Perl::Tk
by pashanoid (Scribe) on Feb 10, 2012 at 11:04 UTC

    This is great! Just one last thing... How would you implement a "Clear" or "Reset" button in this code?

      Just one last thing... How would you implement a "Clear" or "Reset" button in this code?

      How would you? This isn't a code writing service, we just point the way. :-)

      As mentioned in that script, it could be done better, with a single button for start/stop, using $button->configure() to toggle the buttons text and function. To clear it back to zero, from first glance, it looks like the timer data is stored in -textvariable => \$tinfo{'t'}, so zero out $info{'t'} or possibly all of %info's keys.


      I'm not really a human, but I play one on earth.
      Old Perl Programmer Haiku ................... flash japh