use Tk;
require Tk::BrowseEntry;

$numWidgets = 1;
my (@packdirs) = ();
my (@anchordirs) = ();
my (@fill) = ();
my (@expand) = ();

$mw = MainWindow->new(-title => "This is the title");

$f = $mw->Frame(-borderwidth => 1, 
                -relief => 'groove')
                ->pack(-side => 'top', 
                -fill => 'x');

$top = $mw->Toplevel(-title => "output window");
my $addbutton = $f->Button(-text => "Add Widget", 
                           -command => \&addwidget )->pack(-anchor => 'center');
foreach (0..$numWidgets) {
  my $b = $top->Button(-text => $_ . ": $packdirs[$_]")->pack;
  my %pinfo = $b->packInfo;
  $b->packForget;
  &addwidget($_);  
}
MainLoop;

sub repack {
  @w = $top->packSlaves;
  foreach (@w) { $_->packForget; }
  my $e = 0;
  foreach (@w)   {
    $_->configure(-text => "$e: $packdirs[$e]");
    $_->pack(-side => $packdirs[$e], 
             -fill => $fill[$e], 
             -expand => $expand[$e], 
             -anchor => $anchordirs[$e]);
    $e++;
  }
}

sub addwidget {
  my ($count) = @_;
  if (! defined $count)   {
    $numWidgets ++;
    $count = $numWidgets ;
  }
  
  $packdirs[$count] = 'top';
  $anchordirs[$count] = 'center';
  $fill[$count] = 'none';
  $expand[$count] = 0;
  
  my $f1 = $f->Frame->pack(-side => 'top', -expand => 1, 
    -fill =>'y', -before => $addbutton);

  $f1->BrowseEntry(-label => "-fill", -choices => [qw/none x y both/], 
    -variable => \$fill[$count], -browsecmd => \&repack)
    ->pack(-ipady => 5, -side => 'left');



  $top->Button(-text => $count . ": $packdirs[$count]",
    -font => "Courier 20 bold")->pack(-side => $packdirs[$count], 
    -fill => $fill[$count], -expand => $expand[$count]);
}