Search code examples
perltk-toolkitperltk

perltk: highlighting text in textfield and updating labels


Using TK on Windows XP.

my $mw = new MainWindow;
my $text1 = $mw->Text(-width=>20, -height=>10)
            ->place(-x=>350, -y=>460); 

my $showlabel = $mw->Label(-text => "nothing selected")
            ->place(-x=>50, -y=>120);

$text1->configure( -command => sub { 
    $showlabel->configure(-text => "You selected:\t" . 
                          $text1->getSelected() 
                         )
  } 
);

After running the code, $showlabel is not updating whenever I highlight any text. Can anyone please help?


Solution

  • EDIT: code without button.

    And don't forget to call MainLoop at the end of your program to display the window. Without it, nothing will ever happen.

    Try this:

    use strict;
    use warnings;
    
    use Tk;
    
    my $mw = new MainWindow;
    my $text1 = $mw->Text(-width => 20, -height => 10)
                       ->place(-x => 350, -y => 460);
    my $showlabel = $mw->Label(-text => "nothing selectd")
                           ->place(-x => 50, -y => 120);
    $text1->bind('<KeyPress>'     , \&sel);
    $text1->bind('<ButtonPress>'  , \&sel);
    $text1->bind('<ButtonRelease>', \&sel);
    
    MainLoop;
    
    sub sel
    {
        $showlabel->configure(-text => "You selected:\t" . $text1->getSelected);
    }