Hello World!

Being a relative newbie, I was having problems with making Tk Toplevel windows appear over the centre of the main window, and over the centre of the screen. I asked some questions, and got some very complicated answers on how to achieve this, with various geometry commands.

However, today after an inspirational flash, I sorted it all out, so I thought I'd share it.

Spike.

use strict; use warnings; use Tk; my $mw = MainWindow -> new; $mw -> minsize (qw(600 400)); my $button = $mw -> Button ( -text => 'Center of screen', -command => sub {popup('screen')}, ) -> pack; my $other_button = $mw -> Button ( -text => 'Center of main window', -command => sub {popup('window')}, ) -> pack; MainLoop; sub popup { my $type = $_[0]; my $popup = $mw -> Toplevel; $popup -> withdraw; for (1..10) { my $label = $popup -> Label ( -text => "This is a label $_", ) -> pack; } if ($type eq "screen") { $popup -> Popup(); } else { $popup -> Popup ( -popover => $mw, -overanchor => 'c', -popanchor => 'c', ); } }
UPDATE:
(For Win32 systems)
If you use the minsize command on the window that you want to popup, you will discover that it does not get positioned properly. This is due to a bug in the Popup method.

This bug will be fixed in the next release, but if you want to fix it now, then add the marked 3 lines to the Popup subroutine in the following files: C:\Perl\site\lib\auto\Tk\Wm\Popup.al and C:\Perl\site\lib\Tk\Wm.pm

sub Popup { my $w = shift; $w->configure(@_) if @_; $w->idletasks; my ($mw,$mh) = ($w->reqwidth,$w->reqheight); my ($minwidth,$minheight) = $w->minsize; #ADD $mw = $minwidth if (defined $minwidth and $minwidth > $mw); #ADD $mh = $minheight if (defined $minheight and $minheight >$mh); #ADD my ($rx,$ry,$rw,$rh) = (0,0,0,0); ...