How to create equal-width grid columns with Tkinter?
Asked Answered
P

1

9

How can I force the columns in a Tkinter application window to be of equal width?

The tkdocs website states as follows:

The width of each column (or height of each row) depends on the width or height of the widgets contained within the column or row. This means when sketching out your user interface, and dividing it into rows and columns, you don't need to worry about each column or row being equal width [or height, presumably].

TkDocs tutorial: The Grid Geometry Manager

But I want the columns to be equal width, preferably by making the width of all columns depend upon the widest widget in any column. Is there a way of achieving this cleanly (i.e. not by playing around with cell padding until I get them all the same by trial and error or by arbitrarily assigning an apparently adequate minimum width to every column)? Also, can it be selectively done for some, but not all columns in a grid (e.g. so that columns X and Y are are sized according to the widest widget in column X or Y, but column Z is sized according to the widest widget in column Z)?

Peasant answered 8/1, 2014 at 17:35 Comment(0)
F
21

To make a gridded layout have all columns have the same width, you've got to configure those columns to have the same weight and to be in the same uniform group. This configuration is associated with the master widget, not any of the contained widgets (because columns can contain many widgets, of course).

In standard Tk, this is done with:

# "fred" is just some arbitrary key; it means nothing other than to name the group
grid columnconfigure $master 0 -weight 1 -uniform fred

In Tkinter (note that uniform seems to be not documented in the docstring but it is exactly what you need):

# "fred" is just some arbitrary key; it means nothing other than to name the group
master.grid_columnconfigure(0, weight=1, uniform="fred")

Then repeat for the other column indices that you want to set things for. (As you can see, the code's very similar in these two cases.)

Fiery answered 8/1, 2014 at 21:20 Comment(2)
Thanks for the answer, which appears to be correct - hence I've accepted it. I've found that it doesn't solve my problem, but I believe that's because some of my columns are spanned by a single widget. How to deal with this belongs in another question, though.Peasant
I've added another question here making the multi-column widget problem clear: #21009732Peasant

© 2022 - 2024 — McMap. All rights reserved.