16.19. Waiting for Events to Happen

At certain points in your application, it makes sense to wait until something happens. For instance, if you create a ColorEditor window and want it to assign the color the user selects to a variable, you can use waitVariable to wait until the variable is set.

To have a program wait until a variable's value is changed, call waitVariable:

$widget->waitVariable(\$var);

Processing will continue as soon as the value contained within $var is changed to something different. To wait until a $widget is visible, use waitVisibility:

$widget->waitVisibility();

To wait until a widget is destroyed, call waitWindow:

$widget->waitWindow();

When you call these methods, nothing will happen in your program until the requested for event has taken place.

An alternative to waitWindow is OnDestroy, where you specify a callback. The widget methods are still available when you use OnDestory:

$widget->OnDestroy(sub { ... });

16.19.1. File Events

There is a special method in Perl/Tk called fileevent. You can use it to watch and be notified when a file is readable or writable. Here is an example snippet of code that shows how it can be used (this code is meant to be executed on a Unix system because we use the Unix tail command):[1]

[1] Thanks to my friend Phivu Nguyen for sharing his code with me.

use Tk; open (FH, "tail -f -n 25 text_file|") || die "Could not open file!\n"; my $mw = MainWindow->new(); my $text = $mw->Scrolled("Text", -width => 80, -height => 25)->pack(-expand ...

Get Learning Perl/Tk now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.