use Tkx;
my $mw = Tkx::widget->new(".");
$mw->new_button(
-text => "Hello, world",
-command => sub { $mw->g_destroy; },
)->g_pack;
Tkx::MainLoop();
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.
The following functions are provided:
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>.
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>.
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.
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.
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:
The class "Tkx::widget" is used to wrap Tk widget paths. These objects stringify as the path they wrap.
The following methods are provided:
The data hash is automatically destroyed when the corresponding widget is destroyed.
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.
$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.
$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;
The method names with prefix /^_/ and /^[a-zA-Z]_/ are reserved for future extensions to this API.
You can't subclass a Tk widget in Perl, but you can emulate it by creating a megawidget.
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:
See Tkx::LabEntry for a trivial example megawidget.
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.
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>.
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.
Tkx::Tutorial, Tkx::MegaConfig, Tcl
At <http://www.tkdocs.com/tutorial/> you find a very nice Tk tutorial that uses Tkx for the Perl examples.
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>.
The official source repository for Tkx is <http://github.com/gisle/tkx/>.
Alternative Tk bindings for Perl are described in Tcl::Tk and Tk.
ActivePerl bundles a Tcl interpreter and a selection of Tk widgets from ActiveTcl in order to provide a functional Tkx module out-of-box. Tcl::tkkit documents the version of Tcl/Tk you get and whats available in addition to the core commands. You need to set the "PERL_TCL_DL_PATH" environment variable to make Tkx reference other Tcl installations.