Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello

I am trying to write a Tk widget wich will extend functionality of all widgets based on TK::Text. Inheritance should be determined dynamically like in Tk::Scrolled.

Lets say my class name is TextConfig and I want to inject ability to add live links into different widgets. So we can write

$text = $mw->TextConfig('Text'); # or $text = $mw->TextConfig('SuperText'); # or $text = $mw->TextConfig('ROText'); # etc
and receive appropriate widget with extended functionality.

Code of Tk/TextConfig.pm

package Tk::TextConfig; use strict; use Tk; our @ISA; use base qw(Tk::Derived); Construct Tk::Widget 'TextConfig'; sub new { my $package = shift; my $parent = shift; my $kind = shift; my $targetclass = "Tk::$kind"; eval "require $targetclass"; push @ISA, $targetclass; my $object = $targetclass->new($parent, @_); bless $object, "Tk::TextConfig"; # reblessing ? return $object; } my $LinkTagPrefix = 'Link_'; sub insertLink { my ($self, $index, $chars, $action) = @_; my $cnt = ++$self->{'TCcounters'}{'link'}; my $uniquename = $LinkTagPrefix.$cnt; $self->insert($index, $chars, $uniquename); $self->tagConfigure($uniquename, qw/-foreground blue -underline 1 +-data/, $action); # ...... $self->tagBind($uniquename, '<KeyPress>', 'keyLink'); # Wrong # This kind of binding has strange behaviour (bug?) # It is related to the 'current' mark instead of the 'insert'. # So it depends on mouse position # Anyway, it seems that Tk::Text tag bindings has noting common with + widget's bindings # Actually we cannot do Tk->break from sub keyLink }

Code of test.pl

use strict; use Tk; use Tk::TextConfig; my $mw = MainWindow->new; my $text = $mw->TextConfig(qw/Text -height 30/)->pack(qw/-expand 1 -fi +ll both/); for my $i (1..200) { $text->insertLink('end', 'Linktext', 'Some data'); $text->insert('end', ". \n -"); } foreach my $tag ($text->bindtags) { print " bindtag tag '$tag' has these bindings:\n"; print " ", $text->bind($tag), "\n"; } MainLoop();

It looks working. But there is problems with bindtags.

  bindtag tag 'Tk::Text' has these bindings:
  <List of Tk::Text bindings>
  
Tk::Text instead of Tk::TextConfig. Manipulations with bindtags() will lead to more problems.

So questions is:
1) How to solve problem with bindtags? (I would like to redefine some bindings.)
2) Is it correct at all? How to implement dynamic inheritance for Tk widgets?

Replies are listed 'Best First'.
Re: Dynamic inheritance and bindings for TK::Text widgets
by zentara (Cardinal) on Feb 17, 2010 at 19:26 UTC