当我在Perl / Tk中单击该条目/文本时,如何清除条目或文本小部件中的文本

时间:2014-05-27 05:27:14

标签: perl perltk

有人可以将我的问题视为标题吗?我在我创建的表单中有文本和条目小部件,但不知何故,我希望如果我可以做一些文本和条目小部件,我会放置""其中的措辞,如果用户想要使用该条目,他们只需鼠标点击列和""措辞会自动清除。我可以知道怎么做吗? 这是我没有用鼠标点击清除功能的代码。感谢。

#This section apply text  widget.
$mwf->Label(-text => 'Waiver',
    -justify => 'left'
    )->grid(-sticky => 'w', -column => 0, -row => 8);


my $scrollbar = $mwf->Scrollbar() 
->grid( -sticky => 'ns',-column=>2, -row => 8);

my $waiver = $mwf->Text(-height => 5,
        -width => 100,
        -background => "white",
        -wrap => 'word',
        -yscrollcommand => ['set' => $scrollbar], 
        )->grid(-sticky => 'w', -column => 1, -row => 8);

#This section apply entry widget.
$mwf->Label(-text => 'Exclude View',
-justify => 'left'
)->grid(-sticky => 'w', -column => 0, -row => 10);

my $exclude = $mwf->Entry(-width => 100,
        -background => "white",
        )->grid(-sticky => 'w', -column => 1, -row => 10);
        push @entries, $exclude ;
$exclude -> insert('end', '<optional>') ;

1 个答案:

答案 0 :(得分:2)

您可以使用触发事件时调用的绑定

格式$widget->bind('<event>' => callback);

参见下面的示例程序

#!/usr/bin/perl

use strict;
use warnings;
use Tk;
use Tk::Entry;
use Tk::TextUndo;

my $win = new MainWindow;
$win->geometry("400x300");

my $entry = $win->Entry()->pack;
my $text = $win->TextUndo()->pack;
$text->insert('end', 'default');
$entry->insert('end', 'default');

$text->bind('<FocusIn>' => \&textfocus);
$entry->bind('<FocusIn>' => \&entryfocus);
MainLoop;

sub textfocus {

    my $info = $text->Contents();
    if($info =~ /^default$/){
        $text->delete('1.0', 'end');
    }
}

sub entryfocus {
    my $info = $entry->get();
    if($info =~ /^default$/){
        $entry->delete('0.0', 'end');
    }
}

有关perl \ tk事件的更多信息:http://docstore.mik.ua/orelly/perl3/tk/ch15_02.htm#INDEX-2191

编辑:

触发事件时,对调用窗口小部件的引用将传递给回调。 下面是一种只为每个小部件使用一个回调子的方法。

$text->bind('<FocusIn>' => \&w_focus);
$entry->bind('<FocusIn>' => \&w_focus);
MainLoop;

sub w_focus {
    my $widget = shift;
    my ($start, $info);
    if($widget == $text){
        $start = '1.0';
        $info = $widget->Contents();
    }
    else {
        $start = '0.0';
        $info = $widget->get();
    }
    if($info =~ /^default$/){
        $widget->delete($start, 'end');
    }
}
相关问题