alw has asked for the wisdom of the Perl Monks concerning the following question:

Is there any way to display the same widget in 2 different toplevels at the same time? Do I have to clone the widget(don't know if there is a way to do that either). For example:
use Tk; my $mw = new MainWindow; my $lw = $mw->Label(-text=>'on')->pack; my $tl = $mw->Toplevel; MainLoop;
Now how could I get $lw, or a clone of it, to display in $tl? If there is a way to clone a widget, I need to see how to do it also. Thanks

Replies are listed 'Best First'.
Re: Tk widget in 2 toplevels
by liverpole (Monsignor) on Sep 21, 2007 at 13:41 UTC
    Hi alw,

    As the Anonymous Monk said, there isn't a way of cloning a widget.  However, you can achieve similar functionality by just creating a subroutine to handle the details of the widget you wish to "duplicate".

    For example, here's a short program that creates two nearly identical buttons, each on a separate page of a 2-page NoteBook:

    #!/usr/bin/perl -w use strict; use warnings; use Tk; use Tk::NoteBook; # Main program my $mw = new MainWindow(-title => 'Duplicated widget example'); my $nb = $mw->NoteBook()->pack(); my $pg1 = $nb->add("Page 1", -label => "Page 1"); my $pg2 = $nb->add("Page 2", -label => "Page 2"); my $bu1 = add_button($pg1, "Press Me", "I'm a button on Page 1"); my $bu2 = add_button($pg2, "Press Me", "I'm a button on Page 2"); MainLoop; # Subroutines sub add_button { my ($page, $label, $output) = @_; # These attributes will be common to the button my $bg = 'hotpink'; my $width = 20; my $height = 5; my $font = 'Helvetica 20'; # What happens when the button is pressed? my $psub = sub { print "$output\n"; }; # Create the Button widget and pack it my $btn = $page->Button(-bg => $bg, -text => $label); $btn->configure(-font => $font, -width => $width, -height => $heig +ht); $btn->configure(-command => sub { $psub->() }); $btn->pack(); return $btn; }

    The subroutine add_button handles the details of the button you wish to duplicate.  When you call add_button, it adds a button to the specified page of the NoteBook ($1) with the given label ($2) and output text ($3).

    Any other attribute of the button (ie. anything not passed as a subroutine argument) will be the same for each button created.  In the example I've given you, the color, font, and size (height and width) are all constant for any button created with the subroutine.


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: Tk widget in 2 toplevels
by Anonymous Monk on Sep 21, 2007 at 07:32 UTC
    Is there any way to display the same widget in 2 different toplevels at the same time?
    No
    Now how could I get $bw, or a clone of it, to display in $tl? If there is a way to clone a widget, I need to see how to do it also. Thanks
    There is no $bw, but yes, you could use cget to re-create an identical looking widget.