Advanced Perl Programming

Advanced Perl ProgrammingSearch this book
Previous: 14.4 Geometry ManagementChapter 14
User Interfaces with Tk
Next: 14.6 Event Bindings

14.5 Timers

Tk provides a lightweight timer mechanism that can call back a procedure after a specified delay (specified in milliseconds). To create one-shot timers, use the after method on any widget; for repeating timers, use repeat. In the following example, the button changes its label when pressed and resets its label after 300 milliseconds:

$button->configure (text => 'hello',
                    command => \&change_title));
sub change_title {
    my ($old_title) = $button->cget('text');
    $button->configure (text => 'Ouch'); 
    $button->after (300, 
                    sub {$button->configure(text => $old_title)});

We will use after extensively in Chapter 15 for animation.

Both after and repeat return timer objects. Because these mechanisms are quite efficient and lightweight (unlike using alarm() and SIGALRM), you can have a large number of timers. To cancel a timer, use cancel:

$timer = $button->after(100, sub {print "foo"});

Tk's time-out facility, unlike SIGALRM, is not preemptive. It requires that control return to the event loop before it can check if it is time for the next timer to fire. A long subroutine can delay the timed event.

Previous: 14.4 Geometry ManagementAdvanced Perl ProgrammingNext: 14.6 Event Bindings
14.4 Geometry ManagementBook Index14.6 Event Bindings