Flux
Flux

Reputation: 10930

How do I use a grid to center a frame in a window?

I have created a frame containing a label and a button. When I expand the toplevel window, the frame is anchored at the top left of the window. How do I center the frame within the toplevel window? I am using the "grid" geometry manager.

frame .frame
ttk::label .frame.title -text "Rocket 1"
ttk::button .frame.button -text "Launch!"

grid .frame
grid .frame.title
grid .frame.button

GUI created using Tcl/Tk

How do I vertically and horizontally center the label and button?

Upvotes: 0

Views: 379

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137587

You should set the anchoring of the grid within its space. In your case:

grid anchor . center

Note that because you have two grids nested within each other (one in the toplevel, one in the frame) you have to think carefully about which one has the extra space. It's often instructive to set the fill color of frames to something garish (bold red, green, blue, etc) while fixing layout bugs.

To show what I mean, I've added:

# With apologies to people with Daltonism; pick other colours if you prefer
. configure -bg green
.frame configure -bg red

to your script, giving a window like this:

with backgrounds set

Now, if I do:

grid anchor .frame center

it looks identical (the grid of widgets is now centered within the red area that is shrunk-to-fit around them), but if I do:

backgrounds and anchoring

then you can see that the group of widgets on the red background (.frame) is now placed centrally within the green area (.).

Upvotes: 1

Related Questions