0

我正在尝试添加一个带有标准文件打开、保存和新建选项的菜单栏。然而,处理打开、保存和新动作的子例程并没有按预期运行,而是在创建框架时启动。但是,当我真正点击它们时,它不是。

以下是我正在使用的代码。(主窗口仅包含菜单栏)

#!/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";
    }
}
4

1 回答 1

2

那是因为&menu_file('n')调用子例程的语法(更多细节)。相反,你必须这样做:

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

或者像这样:

$mw->bind('<Control-n>' => [\&menu_file, 'n']);
于 2011-05-10T12:21:28.337 回答