in reply to Tk preventing a char in Entry widged to trigger a KeyBinding

Bind toplevel ($mw) to warn on Key-questionmark

also bind so children of $mw of "tag" Tk::Entry break

at first MainWindow has focus, then tab is hit so focus is on the buttons ... when entry has focus nothing is printed

#!/usr/bin/perl -- use strict; use warnings; use Tk; my @t = ( -text => 'focus on me and press ?' ); my $mw = tkinit; $mw->Checkbutton( @t )->pack; $mw->Button( @t )->pack; $mw->Entry( @t )->pack; $mw->bind(q/<Key-?>/,sub{warn "$Tk::widget ? " }); $mw->bind(qw/Tk::Entry <Key-?>/,sub{Tk->break}); MainLoop; __END__ MainWindow=HASH(0xf1eeec) ? at - line 10. MainWindow=HASH(0xf1eeec) ? at - line 10. MainWindow=HASH(0xf1eeec) ? at - line 10. Tk::Checkbutton=HASH(0xf55164) ? at - line 10. Tk::Checkbutton=HASH(0xf55164) ? at - line 10. Tk::Checkbutton=HASH(0xf55164) ? at - line 10. Tk::Checkbutton=HASH(0xf55164) ? at - line 10. Tk::Button=HASH(0xf42c0c) ? at - line 10. Tk::Button=HASH(0xf42c0c) ? at - line 10. Tk::Button=HASH(0xf42c0c) ? at - line 10. Tk::Button=HASH(0xf42c0c) ? at - line 10. Tk::Checkbutton=HASH(0xf55164) ? at - line 10. Tk::Checkbutton=HASH(0xf55164) ? at - line 10. Tk::Checkbutton=HASH(0xf55164) ? at - line 10.

Replies are listed 'Best First'.
Re^2: Tk preventing a char in Entry widged to trigger a KeyBinding -- solution
by Discipulus (Canon) on Oct 12, 2016 at 08:32 UTC
    Thanks to his Anonymousity and all other monks who spent some time to help me.

    I think the bind qw/Tk::Entry <Key-?>/,sub{Tk->break}); is the laziest solution.

    In the case of several TopLevel windows, bindings can be aggregated into a lookup table. Then foreach window any binding is bound to the window and removed for the Tk::Entry class.

    It is also useful to bind <Return> to give back the focus for all Tk::Entry widgets.

    #!/usr/bin/perl use warnings; use strict; use Tk; my $mw = MainWindow->new(); $mw->geometry("200x100+0+0"); $mw->Entry( -text => '',-width => 20)->pack(); $mw->Checkbutton( -text => 'focus on me and press ? or !' )->pack; my $mwbis = $mw->Toplevel(); $mwbis->geometry("200x100+300+0"); $mwbis->Entry( -text => '',-width => 20)->pack(); $mwbis->Checkbutton( -text => 'focus on me and press ? or !' )->pack; # a lookup table for all global bindings my %bind_table = ( '<KeyRelease-?>' => sub{print "A question mark was pressed!!\n"}, '<KeyRelease-!>' => sub{print "A esclamation mark was pressed!!\n"} +, ); foreach my $window ($mw, $mwbis){ # assign bindings to all TopLevel foreach my $bind (keys %bind_table){ $window->bind($bind => $bind_table{$bind}); # remove bindings for all Tk::Entry in all windows $window->bind('Tk::Entry', $bind,sub{Tk->break}); } # bind Return to for Tk::Entry to give the focus to parent $window->bind('Tk::Entry','<Return>' => sub{$_[0]->parent->focus}) } MainLoop;

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.