| 1 |
#!/usr/bin/env perl |
| 2 |
# |
| 3 |
# This script generates a counter with start and stop buttons. Exit with |
| 4 |
# Ctrl/c or Ctrl/q. |
| 5 |
# |
| 6 |
# This a more advanced version of `timer', where we conform to a strict style |
| 7 |
# of Perl programming and thus use lexicals. Also, the counter is updated via |
| 8 |
# a -textvariable rather than a configure() method call. |
| 9 |
# |
| 10 |
# Tcl/Tk -> Perl translation by Stephen O. Lidie. [email protected] 96/01/25 |
| 11 |
|
| 12 |
require 5.002; |
| 13 |
use Tk; |
| 14 |
use strict; |
| 15 |
sub tick; |
| 16 |
|
| 17 |
my $MW = MainWindow->new; |
| 18 |
$MW->bind('<Control-c>' => \&exit); |
| 19 |
$MW->bind('<Control-q>' => \&exit); |
| 20 |
|
| 21 |
# %tinfo: the Timer Information hash. |
| 22 |
# |
| 23 |
# Key Contents |
| 24 |
# |
| 25 |
# w Reference to MainWindow. |
| 26 |
# s Accumulated seconds. |
| 27 |
# h Accumulated hundredths of a second. |
| 28 |
# p 1 IIF paused. |
| 29 |
# t Value of $counter -textvariable. |
| 30 |
|
| 31 |
my(%tinfo) = ('w' => $MW, 's' => 0, 'h' => 0, 'p' => 1, 't' => '0.00'); |
| 32 |
|
| 33 |
my $start = $MW->Button( |
| 34 |
-text => 'Start', |
| 35 |
-command => sub {if($tinfo{'p'}) {$tinfo{'p'} = 0; tick}}, |
| 36 |
); |
| 37 |
|
| 38 |
my $stop = $MW->Button(-text => 'Stop', -command => sub {$tinfo{'p'} = 1;}); |
| 39 |
|
| 40 |
my $counter = $MW->Label( |
| 41 |
-relief => 'raised', |
| 42 |
-width => 10, |
| 43 |
-textvariable => \$tinfo{'t'}, |
| 44 |
); |
| 45 |
|
| 46 |
$counter->pack(-side => 'bottom', -fill => 'both'); |
| 47 |
$start->pack(-side => 'left', -fill => 'both', -expand => 'yes'); |
| 48 |
$stop->pack(-side => 'right', -fill => 'both', -expand => 'yes'); |
| 49 |
|
| 50 |
sub tick { |
| 51 |
|
| 52 |
# Update the counter every 50 milliseconds, or 5 hundredths of a second. |
| 53 |
|
| 54 |
return if $tinfo{'p'}; |
| 55 |
$tinfo{'h'} += 5; |
| 56 |
if ($tinfo{'h'} >= 100) { |
| 57 |
$tinfo{'h'} = 0; |
| 58 |
$tinfo{'s'}++; |
| 59 |
} |
| 60 |
$tinfo{'t'} = sprintf("%d.%02d", $tinfo{'s'}, $tinfo{'h'}); |
| 61 |
$tinfo{'w'}->after(50, \&tick); |
| 62 |
|
| 63 |
} # end tick |
| 64 |
|
| 65 |
MainLoop; |