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{$_} ...

Get Mastering 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.