我需要在perlTk中的文本框设置,以便我可以输入2位数字与自动添加分隔符。
例如:如果在文本框中有5个两位数字的条目,即52、25、69、45、15,如果我输入这5个2位数字,则分隔符(-)应自动添加到每两位数字输入之后。
最终条目将看起来像52 - 25 - 69 - 45 - 15请不要自动插入分隔符。
这有点类似于下面的gif。enter image description here
发布于 2020-05-01 16:03:42
下面是一个示例,说明如何注册在输入小部件中按下某个键时调用的回调。您可以使用此回调在需要时自动插入破折号。
在这里,我使用bind()方法在Tk::Entry小部件上注册按键事件,我还使用-validatecommand来确保用户键入的字符不超过14个:
use feature qw(say);
use strict;
use warnings;
use Tk;
{
my $mw = MainWindow->new();
my $label = $mw->Label(
-text => "Enter serial number",
-justify => 'left'
)->pack( -side => 'top', -anchor => 'w', -padx => 1, -pady =>1);
my $entry = $mw->Entry(
-width => 14,
-state => "normal",
-validate => "key",
-validatecommand => sub { length( $_[0] ) <= 14 ? 1 : 0 }
)->pack(
-side => 'bottom',
-anchor => 'w',
-fill => 'x',
-expand => 1,
);
$entry->bind( '<KeyPress>', sub { validate_entry( $entry ) } );
MainLoop;
}
sub validate_entry {
my ( $entry ) = @_;
my $cur = $entry->get();
my @fields = split "-", $cur;
my $last_field = pop @fields;
for my $field ( @fields ) {
if ( (length $field) != 2 ) {
say "Bad input";
return;
}
}
my $num_fields = scalar @fields;
if ( $num_fields < 4 ) {
if (length $last_field == 2 ) {
$entry->insert('end', '-');
}
}
}https://stackoverflow.com/questions/61537794
复制相似问题