9. How do I get widget X to do Y ?

There are a number of tasks that can be accomplished with perl/Tk widgets, configurations, and bindings (a few that can't and a few that require specific tricks). Beginners are encouraged to work through the examples in UserGuide.pod. Some examples from UserGuide.pod are addressed in this document among those that follow.

Basically a widget can be "created" by simply calling the sub of the same name:

    my $main = new MainWindow;
will set aside the necessary system memory etc. for a new MainWindow widget (it does not appear until after the MainLoop; call). The object "created" is then callable via the variable $main. So, for example, if you wanted a Button in your MainWindow, then this:
    $main->Button();
would be a very basic example of a widget command. If you wanted to later call this button widget you would need a "widget tag or ID" to "get a handle on it". Instead of the above call try something like:
    my $button = $main->Button();
The variable $button is how you refer to the Button widget in subsequent calls, such as when we call the pack routine:
    $button -> pack;
A complete script that incorporates these ideas to make a very plain button would look like:
    #!/usr/bin/perl -w
    use Tk;
    use strict;
    my $main = new MainWindow;
    my $button = $main -> Button();
    $button -> pack;
    MainLoop; 
But who wants such a plain looking button? You can provide a number of different widget configurations via calls to the configure routine as in:
    #!/usr/bin/perl -w
    use Tk;
    use strict;
    my $main = new MainWindow;
    my $button = $main->Button();
    $button -> configure(-text => 'Press me!');
    $button -> pack;
    MainLoop; 
The Perl motto is "there is more than one way to do it." - perl/Tk remains quite true to this motto as well. Note that the above script could have been written quite succinctly without the use of either the $main or $button variables as:
    #!/usr/bin/perl -w
    use Tk;
    use strict;
    new MainWindow -> Button(-text => 'Press me!') -> pack;
    MainLoop; 
But if you want your widgets to actually do things then you must set up callback procedures as discussed later...

As of Tk-b9(.01) the - sign in front of options (like -text in the above example) will be optional (hence ->Button(text => 'Press me!')).


Previous | Return to table of contents | Next