Search code examples
perlcontextmenutk-toolkitperltk

How do I enable a disabled context menu item when selection happens in a Perl Tk gui?


For example in the following script:

use Tk;

my $mw = new MainWindow;
my $t  = $mw->Scrolled("Text")->pack;

my $popup = $mw->Menu(
    -menuitems => [
        [
            Button   => 'Copy Selected',
            -state   => "disabled",
            -command => sub {$t->clipboardColumnCopy}
        ],
    ]
);
$t->menu($popup);

MainLoop;

How do I tell when selection happens so that I can use the following code

$popup->entryconfigure(1, -state=>'normal');

to change the menu item state?

UPDATE:

Big thanks to @Chas and @gbacon :)

I think maybe I can also combine the two good answers:

$t->bind(
    "<Button1-ButtonRelease>",
    sub {
        local $@;
        my $state = defined eval { $t->SelectionGet } ? 
            "normal" : "disable";
        $popup->entryconfigure(1, -state => $state)
    }
);

Solution

  • I don't know Tk very well, but this is an answer (but maybe not the right answer):

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Tk;
    
    my $mw = new MainWindow;
    my $t  = $mw->Text->pack;
    
    
    my $popup = $mw->Menu(
        -menuitems => [
            [ Button => 'Copy Selected', -state => "disabled", -command => sub {$t->clipboardColumnCopy} ],
        ]
    );
    $t->menu($popup);
    
    $t->bind(
        "<Button1-ButtonRelease>",
        sub {
            my $text = $t->getSelected;
            if (length $text) {
                $popup->entryconfigure(1, -state => 'normal');
            } else {
                $popup->entryconfigure(1, -state => 'disabled');
            }
        }
    );
    
    MainLoop;