++ed by:
CAC KRAUTCAT ZMUGHAL DELON

4 PAUSE users
2 non-PAUSE users.

Author image Gisle Aas

NAME

Tkx - Yet another Tk interface

SYNOPSIS

  use Tkx;
  my $mw = Tkx::widget->new(".");
  $mw->new_button(
       -text => "Hello, world",
       -command => sub { $mw->g_destroy; },
  )->g_pack;
  Tkx::MainLoop();

DESCRIPTION

The Tkx module provides yet another Tk interface for Perl. Tk is a GUI toolkit tied to the Tcl language, and Tkx provides a bridge to Tcl that allows Tk based applications to be written in Perl.

The main idea behind Tkx is that it is a very thin wrapper on top of Tcl, i.e. that what you get is exactly the behaviour you read about in the Tcl/Tk documentation with no surprises added by the Perl layer.

The following functions are provided:

Tkx::MainLoop( )

This will enter the Tk mainloop and start processing events. The function returns when the main window has been destroyed. There is no return value.

Tkx::Ev( $field, ... )

This creates an object that if passed as the first argument to a callback will expand the corresponding Tcl template substitutions in the context of that callback. The description of Tkx::foo below explain how callback arguments are provided.

The $field should be a string like "%A" or "%x". The available substitutions are described in the Tcl documentation for the bind command.

Tkx::SplitList( $list )

This will split up a Tcl list into Perl list. The individual elements of the list are returned as separate elements:

    @a = Tkx::SplitList(Tkx::set("a"));

This function will croak if the argument is not a well formed list or if called in scalar context.

Tkx::foo( @args )

Any other function will invoke the foo Tcl function with the given arguments. The name foo first undergo the following substitutions of embedded underlines:

    foo_bar   --> "foo", "bar"   # break into words
    foo__bar  --> "foo::bar"     # access namespaces
    foo___bar --> "foo_bar"      # when you actually need a '_'

This allow us conveniently to map most of the Tcl namespace to Perl. If this mapping does not suit you, use Tkx::i::call($func, @args). This will invoke the function named by $func with no name substitutions or magic.

Examples:

    Tkx::expr("3 + 3");
    Tkx::package_require("BWidget");
    Tkx::DynamicHelp__add(".", -text => "Hi there");
    if (Tkx::tk_windowingsystem() eq "x11") { ... }
    if (Tkx::tk___messageBox( ... ) eq "yes") { ... }

The arguments passed can be plain scalars, array references, code references, or scalar references.

Array references are converted to Tcl lists. The arrays can contain other plain scalars or array references to form nested lists.

For Tcl APIs that require callbacks you can pass a reference to a Perl function. Alternatively an array reference with a code reference as the first element, will allow the callback to receive the rest of the elements as arguments when invoked. If the second element of the array is an Tkx::Ev() object, then the templates it contain will be expanded at the time of the calllback. Some callback examples:

    Tkx::after(3000, sub { print "Hi" });
    Tkx::button(".b", -command [\&Tkx::destroy, "."]);
    Tkx::bind(".", "<Key>", [sub { print "$_[0]\n"; }, Tkx::Ev("%A")]);
    Tkx::bind(".", "<Button-1>", [
       sub {
           my($x, $y) = @_;
           print "Clicked at $x $y\n";
       },
       Tkx::Ev("%x", "%y"),
    ]);

For Tcl APIs that require variables to be passed, you might pass a reference to a Perl scalar. The scalar will be watched and updated in the same way as the Tcl variable would.

The Tcl string result is returned in both scalar and array context. Tcl errors are propagated as Perl exceptions.

If the boolean variable $Tkx::TRACE is set to a true value, then a trace of all commands passed to Tcl will be printed on STDERR. This variable is initialized from the PERL_TKX_TRACE environment variable. The trace is useful for debugging and if you need to report errors to the Tcl maintainers in terms of Tcl statements. The trace lines are prefixed with:

    Tkx-$seq-$ts-$file-$line:

where $seq is a sequence number, $ts is a timestamp in seconds since the first command was issued, and $file and $line indicate on which source line this call was triggered.

All these functions can be exported by Tkx if you grow tired of typing the Tkx:: prefix. Example:

    use strict;
    use Tkx qw(MainLoop button pack destroy);

    pack(button(".b", -text => "Press me!", -command => [\&destroy, "."]));
    MainLoop;

No functions are exported by default.

Widget handles

The class Tkx::widget is used to wrap Tk widget paths or names. These objects stringify as the path they wrap.

The following methods are provided:

Tkx::widget->_Mega( $widget, $class )

This register $class as the one implementing $widget widgets. See "Megawidgets".

$w = Tkx::widget->new( $path )

This constructs a new widget handle for a given path. It is not a problem to have multiple handle objects to the same path or to create handles for paths that does not exist yet.

$w->_data

Returns a hash that can be used to keep instance specific data. This is useful for holding instance data for megawidgets. The data is attached to the underlying widget, so if you create another handle to the same widget it will return the same hash via its _data() method.

The data hash is automatically destroyed when the corresponding widget is destroyed.

$w->_parent

Returns a handle for the parent widget. Returns undef if there is no parent, which will only happen if $w is ".", the main window.

$w->_kid( $name )

Returns a handle for a kid widget with the given name. The $name can contain dots to access grandkids. There is no check that a kid with the given name actually exists, so this method can't fail. This is a feature. It can for instance be used to construct names of widgets to be created later.

$w->_class( $class )

Sets the widget handle class for the current path. This will both change the class of the current handle and make sure later handles created for the path belong to the given class. The class should normally be a subclass of Tkx::widget. Overriding the class for a path is useful for implementing megawidgets. Kids of $w are not affected by this, unless the class overrides the _nclass method.

$w->_nclass

This returns the default widget handle class that will be used for kids and parent. Subclasses might want to override this method. The default implementation always returns Tkx::widget.

$w->_mpath( $method )

This returns a Tcl widget path that will be used to forward any m_foo method calls. Megawidget classes might want to override this method. The default implementation returns $w.

$new_w = $w->new_foo( @args )

This creates a new foo widget as a child of the current widget. It will call the foo Tcl command and pass it a new unique subpath of the current path. The handle to the new widget is returned. Any double underscores in the name foo is expanded as described for Tkx::foo() above.

Example:

    $w->new_label(-text => "Hello", -relief => "sunken");

The name selected for the child will be the first letter in the widget. If that name is not unique a number is appended to ensure uniqueness among the children. If a -name argument is passed it is used to form the name and then removed from the arglist passed to Tcl. Example:

    $w->new_iwidgets__calendar(-name => "cal");

If a megawidget implementation class has be registered for foo, then its _Populate method is called instead of passing widget creation to Tcl.

$w->m_foo( @args )

This will invoke the foo subcommand for the current widget. This is the same as:

    $func = "Tkx::$w";
    &$func(expand("foo"), @args);

where the expand() function expands underscores as described for Tkx::foo() above. Note that methods that do not start with a prefix of the form /^_/ or /^[a-zA-Z]_/ are also treated as the m_ methods.

Example:

    $w->m_configure(-background => "red");

Subclasses might override the _mpath() method to have m_foo forward the subcommand somewhere else than the current widget.

$w->g_foo( @args )

This will invoke the foo Tcl command with the current widget as first argument. This is the same as:

    $func = "Tkx::foo";
    &$func($w, @args);

Any underscores in the name foo are expanded as described for Tkx::foo() above.

Example:

    $w->g_pack_forget;
$w->foo( @args )

If the method does not start with "new_" or have a prefix of the form /^_/ or /^[a-zA-Z]_/, then it is treated as if it had the "m_" prefix, i.e. the foo subcommand for the current widget is invoked.

The method names with prefix /^_/ and /^[a-zA-Z]_/ are reserved for future extensions to this API.

Megawidgets

Megawidgets can be implemented in Perl and used by Tkx. To declare a megawidget make a Perl class like this one:

    package Foo;
    use base 'Tkx::widget';
    Foo->_Mega("foo");

    sub _Populate {
        my($class, $widget, $path, %opt) = @_;
        ...
    }

The megawidget class should inherit from Tkx::widget and will register itself by calling the _Mega() class method. In the example above we tell Tkx that any "foo" widgets should be handled by the Perl class "Foo" instead of Tcl. When a new "foo" widget is instantiated with:

    $w->new_foo(-text => "Hi", -foo => 1);

then the _Populate() class method of Foo is called. It will be passed the widget type to create, the full path to use as widget name and any options passed in. The widget name is passed in so that a single Perl class can implement multiple widget types.

The _Populate() class should create a root object with the given $path as name and populate it with the internal widgets. Normally the root object will be forced to belong to the implementation class so that it can trap various method calls on it. By using the _class() method to set class _Populate() can ensure that new handles to this megawidget also use this class.

The implementation class can define an _ipath() method to delegate any m_foo method calls to one of its subwidgets and it might want to override the m_configure() and m_cget() methods if it implements additional options or want more control over delegation. The class Tkx::MegaConfig provide implementations of m_configure() and m_cget() that can be useful for controlling delegation of configuration options.

See Tkx::LabEntry for a trivial example megawidget.

ENVIRONMENT

The PERL_TKX_TRACE environment variable initialize the $Tkx::TRACE setting.

SUPPORT

If you have questions about this code or want to report bugs send a message to the <tcltk@perl.org> mailing list. To subscribe to this list send an empty message to <tcltk-subscribe@perl.org>.

LICENSE

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Copyright 2005 ActiveState. All rights reserved.

SEE ALSO

Tkx::Tutorial, Tkx::MegaConfig, Tcl

Alternative Tk bindings for Perl are described in Tcl::Tk and Tk.

More information about Tcl/Tk can be found at http://www.tcl.tk/. Tk documentation is also available at http://aspn.activestate.com/ASPN/docs/ActiveTcl/at.pkg_index.html.