Need a text box help in PerlTk

119 Views Asked by At

I need a text box setting in perlTk such that i can enter 2 digit number with automatically added separator.

Eg. if there are 5 entries of two digits number namely 52, 25, 69, 45, 15, in text box if i enter these five 2 digits numbers the separator (-) should automatically added after every two digit entry.

and final entry would look like 52 - 25 - 69 - 45 - 15 Please not that separator should automatically inserted.

This is somewhat similar to below gif. enter image description here

1

There are 1 best solutions below

0
Håkon Hægland On BEST ANSWER

Here is an example of how you can register a callback to be called when a key is pressed in an entry widget. You can use this callback to insert a dash automatically when needed.

Here I am using the bind() method to register keypress events on a Tk::Entry widget, I also use -validatecommand to ensure the user does not type in more than 14 characters:

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', '-');
        }
    }
}