This function centers a Tk::Toplevel on the screen, taking into account the window's width and height.

Caveat: To get the correct window size, the function has to force the window to update, which causes the window to be displayed if it wasn't. If you want the window to end hidden, leave out the deiconify, near the end.

sub center {
  my $win = shift;

  $win->withdraw;   # Hide the window while we move it about
  $win->update;     # Make sure width and height are current

  # Center window
  my $xpos = int(($win->screenwidth  - $win->width ) / 2);
  my $ypos = int(($win->screenheight - $win->height) / 2);

  $win->deiconify;  # Show the window again