use strict; use warnings; use Tk; my $mw = MainWindow->new ; my $canvas ; my $text ; my $text_var = 'Canvas example' ; my $text_len = length( $text_var ) ; my $cur_pos = $text_len ; my $width = 200 ; my $height = 100 ; $mw->title( 'Canvas Example' ) ; $canvas = $mw->Canvas( -background => 'white', -width => $width, -height => $height, -scrollregion => [ 0, 0, 500, 500 ], ) ; $canvas->CanvasFocus() ; $text = $canvas->createText( 100, 90, -text => $text_var, -tags => 'title', ) ; $canvas->focus( $text ) ; $canvas->icursor( $text, $cur_pos ) ; $canvas->bind( 'title', '' => \&updater ) ; my $exit = $mw->Button( -text => 'Exit', -command => [$mw => 'destroy'], ) ; $canvas->pack; $exit->pack; ######### MainLoop; ######### #function to manipulate text in the field or to move cursor around sub updater { my ( $k ) = @_ ; my $e = $k->XEvent ; #get event object my $k_val = $e->N ; #get decimal equivalent my $k_str = $e->K ; #get ascii equivalent #print "updater $k_val\n" ; #should move the cursor to left in text if( $k_str eq 'Left' ) { $cur_pos = $cur_pos > 0 ? $cur_pos - 1 : 0 ; } elsif( $k_str eq 'Right' ) { $cur_pos = $cur_pos < length( $text_var ) ? $cur_pos + 1 : length( $text_var ) ; } else{ #append new char to the text $text_var .= $k_str ; $text_len = length( $text_var ) ; $cur_pos++ ; #show updated text $canvas->itemconfigure( -text => $text_var, -tags => 'title', ) ; } $canvas->icursor( $text, $cur_pos ) ; }