
原文:
11.10. How do I bind different actions to different areas of the same Canvas?
KOBAYASI Hiroaki recently posted an extraordinary little script that addresses this question quite succinctly:
How about this?
## I don’t know whether this is a good solution or not.
## but it works under Tk-b9 + perl5.002b1f.
#!/usr/local/bin/perl -w use Tk; ($c = MainWindow->new->Canvas)-> pack(-fill => ’both’, -expand => 1); # to survive under Tk-b8. # You don’t need paren before pack in b9. ($pop1 = $c->Menu)->command(-label => "FOO"); ($pop2 = $c->Menu)->command(-label => "BAR"); $c->create(oval => 0, 0, 100, 100, -fill => ’black’, -tags => [’popup’]); $c->Tk::bind($c, ’<3>’, [\&PopupOnlyThis, $pop1]); $c->bind(’popup’, ’<3>’, [\&PopupOnlyThis, $pop2]); sub PopupOnlyThis { print "@_\n"; my($c, $pop) = @_; # to prevent multiple popup. Tk->break if defined $Tk::popup; my $e = $c->XEvent; $pop->Popup($e->X, $e->Y); # Tk::Menu::Popup sets $Tk::popup. } MainLoop; $Tk::popup = undef; # to kill warning. __END__
译文:
11.10. 怎样给画布的不同区域配置不同的绑定?
KOBAYASI Hiroaki最近贴出了一个很短小的脚本能够很简洁的说明这个问题:
怎么样?
##我不知道这是否算是个很好的解决方法。
##但是他能够在Tk-b9 + perl5.002b1f的环境下运行。(译者注:下面的脚本已被修改以便能够在Tk8+perl5下较好的运行。)
#!/usr/local/bin/perl -w
use Tk;
($c = MainWindow->new->Canvas)->
pack(-fill => ’both’, -expand => 1);
($pop1 = $c->Menu(-tearoff=>0))->command(-label => "FOO");
($pop2 = $c->Menu(-tearoff=>0))->command(-label => "BAR");
$c->create(oval => 0, 0, 100, 100,
-fill => ’black’,
-tags => [’popup’]);
$c->Tk::bind($c, ’<3>’, [\&PopupOnlyThis, $pop1]);
$c->bind(’popup’, ’<3>’, [\&PopupOnlyThis, $pop2]);
sub PopupOnlyThis {
print "@_\n";
my($c, $pop) = @_;
# to prevent multiple popup.
return if defined $Tk::popup;
my $e = $c->XEvent;
$pop->post($e->X, $e->Y);
# Tk::Menu::post sets $Tk::popup.
}
MainLoop;
$Tk::popup = undef; # to kill warning.
__END__
(译者注:个人感觉这个脚本有点“喧宾夺主”了。因为这里的主题是怎样对不同的区域分别进行绑定,所以其实答案就是给需要绑定的特别区域加上标签??例如上面的圆’popup’??这样就能够在配置绑定的时候直接使用这个标签了!而这个例子中配置的这个弹出菜单有点惹眼??至少我是研究了半天……所以,等我把他调通以后都忘记了这个例子是要说明什么了……:P 记得前面曾有人问过怎么做这样的弹出菜单的,这个脚本应该能够算是个不错的例子了吧。)
|