#!/usr/bin/perl -w # # This script generates a counter with start and stop buttons. # You can exit the program with Ctrl/c or Ctrl/q. # # This a more advanced version of `timer', where we conform to a # strict style of Perl programming and thus use lexicals. # Also, the counter is updated via # a -textvariable rather than a configure() method call. # # Original by Stephen O. Lidie. lusol@Lehigh.EDU 96/01/25 use Tk; use strict; our $main = MainWindow->new; # Define what happens when control-c and control-q are pressed. $main->bind('' => \&exit); $main->bind('' => \&exit); # Set up a pull-down menu across the top of the frame. our $menuFrame = $main->Frame( -relief=>'ridge', -borderwidth=>2); $menuFrame->pack( -side=>'top', -anchor=>'n', -expand=>1, -fill=>'x'); $menuFrame->Menubutton( -text=>'About', -menuitems=>[ [ "command"=>"About xTimer...", -command =>\&about ], [ "command"=>"Print 'hello'", -command =>\&printHello ], [ "command"=>"Quit", -command =>\&exit ], ] )->pack(-side=>'right'); # the Timer Information hash. our %tinfo = ('s' => 0, # accumulated seconds. 'h' => 0, # accumulated hundredths of a second. 'p' => 1, # 1 if paused. 't' => '0.00', # value of $counter -textvariable ); # Create a button to start the timer. our $start = $main->Button( -text => 'Start', -command => sub { if ($tinfo{'p'}) { $tinfo{'p'} = 0; tick(); } }, ); # Create a button to stop the timer. our $stop = $main->Button( -text => 'Stop', -command => sub { $tinfo{'p'} = 1; } ); # And create a label to show the time. my $counter = $main->Label( -relief => 'raised', -width => 10, -textvariable => \$tinfo{'t'}, ); # Put the three widgets into the window. $counter->pack( -side => 'bottom', -fill => 'both'); $start->pack( -side => 'left', -fill => 'both', -expand => 'yes'); $stop->pack( -side => 'right', -fill => 'both', -expand => 'yes'); # And run the program. MainLoop; # -- subroutines ----------------------------------------------- # tick() reinvokes itself every 50 milliseconds, or 5 hundredths of a second. # It's invoded the first time when the "start" button is pressed. sub tick { return if $tinfo{'p'}; # Don't do anything if we're paused. $tinfo{'h'} += 5; if ($tinfo{'h'} >= 100) { $tinfo{'h'} = 0; $tinfo{'s'}++; } $tinfo{'t'} = sprintf("%d.%02d", $tinfo{'s'}, $tinfo{'h'}); $main->after(50, \&tick); } # end tick # A pop-up dialog box. sub about { use Tk::Dialog; my $aboutText = "This is just a little demo of the Perl/Tk GUI library routines." . "It has a little menu, a couple of buttons, and runs a timer.\n\nSo there. "; $main->Dialog( -text => $aboutText, -title => "About xTimer", -default_button => "Yes", -buttons => ["Ok"])->Show();; } # Some other random action. sub printHello { print "Hello...\n"; }