15.3. Creating a Composite Widget Based on Frame

There are slight differences between creating a composite widget based on a frame and creating one based on a toplevel. I will include a short example for each to give you an idea of what you can do.

Assuming you're making a composite widget called MyWidget, the first five lines you absolutely must have in your new composite widget file are:

package MyWidget;
require Tk::Frame;
@ISA = qw(Tk::Frame);

Construct Tk::Widget 'MyWidget';

sub Populate

You must declare your new widget as its own package, hence the package MyWidget line. (If you were going to have a subdirectory for your widgets, you would use DirName::MyWidget.)

The next two lines are simple: require Tk::Frame to make sure you have loaded the information necessary to use a frame widget, and then add Tk::Frame to the @ISA variable. The next line calls the Construct method from Tk::Widget (you could also write this as Tk::Widget->Construct("MyWidget")) with the name of your widget. In this call to Construct you do not add the name of the directory in which your widget resides.

By calling Construct, you create a constructor method for your new MyWidget widget. This allows you to create a new MyWidget by calling the MyWidget method:

$newwidget = $mw->MyWidget(...);

You are creating a composite widget based on a frame, so you need to use Populate to create your subwidgets and do any other necessary configuration.

15.3.1. Inside Populate

It is a good idea to add a

Get Learning Perl/Tk now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.