O'Reilly logo

Mastering Perl/Tk by Nancy Walsh, Stephen Lidie

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Synthesizing Virtual Events

Tk supports a generic event command to define, generate, query, and delete virtual events. These are events that we make (or are made on our behalf) above and beyond those in Tk. We’ve mentioned the eventGenerate method previously, which generates events just as if they’d come from the window system. Using eventGenerate, we can simulate a person typing characters and clicking buttons, as well as invoking other real and virtual events.

The following code “types” the characters “Hello Perl/Tk” in the Entry widget $e. It’s important to note that the Entry widget must have the keyboard focus, otherwise the data falls into the bit bucket. The update command is also important, as it ensures that all events have been processed. $evar is the Entry’s -textvariable and, if all goes well, it will contain the “typed” characters.

my %keysyms = (' ' => 'space', '/' => 'slash');
my $evar;
my $e = $mw->Entry(-textvariable => \$evar)->pack;

$b = $mw->Button(
    -text    => 'Show $evar',
    -command => sub {print "$evar\n"},
)->pack;

$e->focus;
$mw->update;			# prevents lost characters

Figure 15-8 shows the outcome.

Data synthesized by eventGenerate

Figure 15-8. Data synthesized by eventGenerate

Here’s the input loop. Most of the characters in the string "Hello Perl/Tk" are their own keysyms, but for those that aren’t, we provide a mapping through the hash %keysysms.

foreach (split '', 'Hello Perl/Tk') { $_ = $keysyms{$_} ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required