in reply to read Tk Text Widget when content changes

Hello Anonymous Monk,

you can profit the <<Modified>> virtual event (see it here), for a first-time-only modification, like in,

use strict; use warnings; use Tk; my $mw = new MainWindow; my $text = $mw->Text(qw/-width 40 -height 10/)->pack; my $current_color = "black"; $text->configure(-insertbackground => $current_color); $text->configure(-cursor => "arrow"); my $button = $mw->Button(-text => "Quit", -command => sub { exit })->p +ack; $text->bind('<<Modified>>', sub{warn "text changed\n"} ); MainLoop;

And you c an also play resetting $text->editModified to zero but follow what our wise zentara said about avoinding an infinite loop: Re: Using Tk::Text and '<<Modified>>'

See also Onchange-like event handler for Tk text widget

L*

PS you can have a better control, but still not optimale with:

my $len; .. $text->bind('<<Modified>>', sub{ if ($len != length $text->Contents ){ $len = length $text->Contents; warn "text changed ($len)\n"; $text->editModified(0) } } );

or better (but breaks on backspaces..)

$text->bind('<<Modified>>', sub{ if ($len ne $text->Contents ){ $len = $text->Contents; warn "text changed\n"; $text->editModified(0) } } );

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: read Tk Text Widget when content changes
by Anonymous Monk on Aug 07, 2017 at 12:34 UTC

    Thank you very much!

    After playing a bit with the tips and examples provided I came up with this solution which seems to suit perfectly

    use warnings; use strict; use Tk; my $mw = MainWindow->new(); my $tx = $mw->Text()->pack(); $tx->bind( '<<Modified>>' => \&readTextWidget); my $CursorPosition="1.0"; MainLoop; sub readTextWidget{ if ($tx->editModified()) { my @Text=$tx->dump($CursorPosition,'end'); my $TextChunk = $Text[1]; $CursorPosition= $Text[5]; my @words = split / /, $TextChunk ;#very basic tokenizer for t +he moment foreach my $word (@words) { print "$word\n"; } $tx->editModified(0); } }