Tkx(3) 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.

This is the ``reference manual'' for Tkx. For a gentle introduction please read the Tkx::Tutorial. The tutorial at <http://www.tkdocs.com/tutorial/> is also strongly recommended.

Functions

The following functions are provided:
Tkx::AUTOLOAD( @args )
All calls into the "Tkx::" namespace not explicitly listed here are trapped by Perl's AUTOLOAD mechanism and turned into a call of the corresponding Tcl or Tk command. The Tcl string result is returned as a single value in both scalar and list context. Tcl errors are propagated as Perl exceptions.

For example:

    $res = Tkx::expr("3 + 3")

This will call the Tcl command "expr" passing it the argument "3 + 3" and return the result back to Perl. The value of $res after this call should be 6.

The exact rules for mapping functions names into the Tcl name space and the details of passing arguments to Tcl is described in ``Calling Tcl and Tk Commands'' below.

Don't call Tkx::AUTOLOAD() directly yourself.

The available Tcl commands are documented at <http://www.tcl.tk/man/tcl/TclCmd/contents.htm>. The available Tk commands are documented at <http://www.tcl.tk/man/tcl/TkCmd/contents.htm>.

Tkx::Ev( $field, ... )
This creates an object that if set up as the first argument to a callback will expand the corresponding Tcl template substitutions in the context of that callback. ``Callbacks to Perl'' 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; see <http://www.tcl.tk/man/tcl/TkCmd/bind.htm>.

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::SplitList( $list )
This will split up a Tcl list into a Perl list. The individual elements of the list are returned as separate elements. This function will croak if the argument is not a well formed list or if called in scalar context.

Example:

    my @list = Tkx::SplitList("a {b c}");
    # @list is now ("a", "b c")

This function is needed because direct calls Tcl don't expand lists even if called in list context, so if you want to process the elements returned as a Tcl list you need to wrap the call in a call to SplitList:

    for my $file (Tkx::SplitList(Tkx::glob('*.pm'))) {
        # ...
    }

Since Perl also have a built in glob function there is no need to actually let Tcl do the globbing for you. The example above is purely educational.

The Tkx::list() function would invoke the Tcl command that does the reverse operation --- creating a list from the arguments passed in. You seldom need to call Tkx::list() explicitly as arrays are automatically converted to Tcl lists when passed as arguments to Tcl commands.

All these functions, even the autoloaded ones, 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.

Calling Tcl and Tk Commands

Tcl and Tk commands are easily invoked by calling the corresponding function in the Tkx:: namespace. Calling the function "Tkx::expr()" will invoke the "expr" command on the Tcl side. Function names containing underlines are a bit special. The name passed from the Perl side undergo the following substitutions:

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

This allow us conveniently to map the Tcl namespace to Perl. If this mapping does not suit you, an alternative is to use "Tkx::i::call($cmd, @args)". This will invoke the command named by $cmd 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") { ... }

One part of the Tcl namespace that is not conveniently mapped to Perl using the rules above are commands that use ``.'' as part of their name, mostly Tk widget instances. If you insist you can invoke these by quoting the Perl function name

    &{"Tkx::._configure"}(-background => "black");

or by invoking this as "Tkx::i::call(".", "configure", "-background", "black")"; but the real solution is to use "Tkx::widget" objects to wrap these as described in ``Widget handles'' below.

Passing arguments

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

Plain scalars (strings and numbers) as just passed on unchanged to Tcl.

Array references, where the first element is not a code reference, are converted into Tcl lists and passed on. The arrays can contain strings, numbers, and/or array references to form nested lists.

Code references, and arrays where the first element is a code reference, are converted into special Tcl command names in the ``::perl'' Tcl namespace that will call back into the corresponding Perl function when invoked from Tcl. See ``Callbacks to Perl'' for a description how how this is used.

Scalar references are converted into special Tcl variables in the ``::perl'' Tcl namespace that is tied to the corresponding variable on the Perl side. Any changes to the variable on the Perl side will be reflected in the value on the Tcl side. Any changes to the variable on the Tcl side will be reflected in the value on the Perl side.

Hash references are converted into special Tcl array variables in the ``::perl'' Tcl namespace that is tied to the corresponding hash on the Perl side. Any changes to the hash on the Perl side will be reflected in the array on the Tcl side. Any changes to the array on the Tcl side will be reflected in the hash on the Perl side.

Anything else will just be converted to strings using the Perl rules for stringification and passed on to Tcl.

Tracing

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/Tk 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.

Callbacks to Perl

For Tcl APIs that require callbacks you can provide a reference to a Perl subroutine:

    Tkx::after(3000, sub { print "Hi" });
    $button = $w->new_button(
        -text    => 'Press Me',
        -command => \&foo,
    );

Alternately, you can provide an array reference containing a subroutine reference and a list of values to be passed back to the subroutine as arguments when it is invoked:

    Tkx::button(".b", -command => [\&Tkx::destroy, "."]);
    $button = $w->new_button(
        -text    => 'Press Me',
        -command => [\&foo, 42],
    );

When using the array reference syntax, if the second element of the array (i.e. the first argument to the callback) is a Tkx::Ev() object the templates it contains will be expanded at the time of the callback.

    Tkx::bind(".", "<Key>", [
        sub { print "$_[0]\n"; }, Tkx::Ev("%A")
    ]);
    $entry->configure(-validatecommand => [
        \&check, Tkx::Ev('%P'), $entry,
    ]);

The order of the arguments to the Perl callback code is as follows:

1.
The expanded results from Tkx::Ev(), if used.
2.
Any arguments that the command/function is called with from the Tcl side. For example, in callbacks to scrollbars Tcl provides values corresponding to the visible portion of a scrollable widget. Tcl arguments are passed regardless of the syntax used when specifying the callback.
3.
Any extra values provided when the callback defined; the values passed after the Tkx::Ev() object in the array.

Widget handles

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

The following methods are provided:

$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 do not yet exist.
$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; which can be taken advantage of to construct names of Tk widgets to be created later.
$w->_kids
Returns all existing kids as widget objects.
$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 method determine the Tk widget path that will be invoked for m_foo method calls. The argument passed in is the method name without the "m_" prefix. Megawidget classes might want to override this method. The default implementation always 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 in ``Calling Tcl and Tk Commands'' above.

Example:

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

The name selected for the child will be the first letter of the widget type; for the example above ``l''. 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 as the name and then removed from the arglist passed on 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 in ``Calling Tcl and Tk Commands'' above.

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 in ``Calling Tcl and Tk Commands'' 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]_/, the call will just forward to the method "m_foo`` (described above). This is just a convenience for people that have grown tired of the ''m_" prefix.

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

Tkx::widget->_Mega( $widget, $class )
This register $class as the one implementing $widget widgets. See ``Megawidgets''.

Subclassing Tk widgets

You can't subclass a Tk widget in Perl, but you can emulate it by creating a megawidget.

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 the class _Populate() can ensure that new handles to this megawidget also use this class.

To make Tk aware of your megawidget you must register it by providing a "-class" argument when creating the root widget. Doing this sets the value returned by the "$w->g_winfo_class" method. It also makes it possible for your megawidget to have to have class-specific bindings and be configurable via Xdefaults and the options database. By convention class names start with a capital letter, so Tkx megawidgets should have names like ``Tkx_Foo''. If you don't register your megawidget with Tk, "g_winfo_class" will return the class of whatever you use as a root widget and your megawidget will be subject to the bindings for that class.

Of the standard Tk widgets only frames support "-class" which means that (practically speaking) Tkx megawidgets must use a frame as the root widget. The ttk widgets do support "-class", so you may be able to dispense with the frame if your megawidget is really just subclassing one of them.

The implementation class can (and probably should) define an _mpath() method to delegate any m_foo method calls to one of its subwidgets. It might want to override the m_configure() and m_cget() methods if it implements additional options or wants 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.

Public methods defined by a megawidget should have an ``m_'' prefix. This serves two purposes:

  • It makes them behave the same as native widget methods. That is, they may be called either with or without the ``m_'' prefix as the user of the widget prefers.
  • It enables the megawidget to accept method delegation from another widget via the parent widget's _mpath() method.

See Tkx::LabEntry for a trivial example megawidget.

ENVIRONMENT

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

The "PERL_TCL_DL_PATH" environment variable can be set to override the Tcl/Tk used.

SUPPORT

If you have questions about this code or want to report bugs send a message to the <[email protected]> mailing list. To subscribe to this list send an empty message to <[email protected]>.

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.