Perl/Tk menubar quirks

a 夏天 提交于 2019-12-25 03:36:22

问题


I'm trying to add a menubar with the standard File Open, Save and New options. However, instead of behaving as expected, the subroutine handling the open, save and new actions is launched upon creation of the frame. But, when I actually click on them, it is not.

Following is the code I'm using. (Main window contains only the menubar)

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;
use Data::Dumper;

use Tk 8.0;
use Tk::NoteBook;
use Tk::MsgBox;



my $mw=MainWindow->new;
$mw->geometry("+500+300");

# Menu Bar Buttons
my $mbar=$mw->Menu();
$mw->configure(-menu => $mbar);
    my $file=$mbar->cascade(-label=>"~File", -tearoff => 0);
    my $help=$mbar->cascade(-label =>"~Help", -tearoff => 0);
# File Menu
    $file->command(-label =>'~New     ', -command=>&menu_file('n'), -accelerator=>'Ctrl+N');
    $file->command(-label =>'~Open    ', -command=>&menu_file('o'), -accelerator=>'Ctrl+O');
    $file->command(-label =>'~Save    ', -command=>&menu_file('s'), -accelerator=>'Ctrl+S');
    $file->separator();
    $file->command(-label =>'~Quit    ', -command=>sub{exit}, -accelerator=>'Ctrl+Q');
# Help Menu
    $help->command(-label => 'Version');
    $help->separator;
    $help->command(-label => 'About');

# Menu Bar Accelerators
    $mw->bind('<Control-n>', &menu_file('n'));
    $mw->bind('<Control-o>', &menu_file('o'));
    $mw->bind('<Control-s>', &menu_file('s'));
    $mw->bind('<Control-q>', sub{exit});


MainLoop;



sub menu_file {
    my $opt=shift;

    my $filetypes = [
        ['Codac files', '.k'],
        ['All Files',  '*'  ],
    ];

    if($opt eq 's'){
        my $txt_ent_script = $mw->getSaveFile(-filetypes=>$filetypes, -initialfile=>'jitter', -defaultextension=>'.k');
        print "Output filename: $txt_ent_script\n";
    }
}

回答1:


That's because &menu_file('n') is syntax for invoking a subroutine (more details). Instead, you have to do it like this:

$mw->bind('<Control-n>' => sub{menu_file('n')});

Or like this:

$mw->bind('<Control-n>' => [\&menu_file, 'n']);


来源:https://stackoverflow.com/questions/5947681/perl-tk-menubar-quirks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!