Search code examples
perltk-toolkitkey-bindingsperltk

Perl Tk Key Binding to Enter


I try to make a GUI which has $cmd_entry to take the input and print the input on $log_frame after "enter" key is pressed. However, the binding does not work well. I do not know why the callback function will work some times but not for some times. When I change the key binding to , it works once when I pressed "Tab" twice.

use Tk;
use Tk::ROText;

my $configuration_window = MainWindow->new(-title => "Testing");
$configuration_window->geometry("1024x800");

my $log_frame = $configuration_window->Scrolled("ROText", -scrollbars => 'os',-background => "white",-foreground => "black")->pack(-side => 'left', -expand => 1, -fill => 'both', -padx => 4, -pady => 4);
my $list_frame = $configuration_window->Frame(-borderwidth => 1, -relief => 'groove')->pack(-side => 'right', -fill => 'both', -expand => 1, -padx => 4, -pady => 4);
my $cmd_entry = $log_frame->Entry(-background => "white")->pack(-side => "bottom", -fill => 'x');

$cmd_entry->bind(ref $cmd_entry,'<Enter>',sub {sendLog("enter");});

$log_frame->insert('end', "> ");

MainLoop;

sub sendLog{
    my ($text) = @_;
    $log_frame->insert('end', "$text\n> ");
}

Solution

  • This line has a couple of problems:

    $cmd_entry->bind(ref $cmd_entry,'<Enter>',sub {sendLog("enter");});
    

    a) bind does not take a reference to the entry widget as the first argument.

    b) The '<Enter>' bind tag refers to the event when the widget is entered via the mouse or keyboard, not the enter key, which is <Return>.

    Try:

    $cmd_entry->bind('<Return>',sub {sendLog("enter");});
    $cmd_entry->bind('<Tab>',sub {sendLog("tab");});