Is it possible in tkinter to have two columns of labels with one label below and in the middle of them?

fozbstuios picture fozbstuios · Aug 7, 2013 · Viewed 13.3k times · Source

example

While the picture shows basically what I want to do, however:

  1. All labels supposed to be perfect squares of the same size
  2. labels in the 2 columns should be perfectly aligned
  3. The label at the bottom should be perfectly below and in the middle of the other two.
  4. The actual labels should be solid and there should be a little space around the text of the label(text shouldn't take up the whole label).

Grid should be used if possible. I'll use python3

Answer

Bryan Oakley picture Bryan Oakley · Aug 7, 2013

Yes, of course it is possible. Tkinter arguably has the most flexible and easy to use geometry managers of any GUI toolkit. With just pack, place, and grid there is probably no layout you can't do.

Start with a piece of paper. Seriously. Until you are able to visualize this, use paper.

Draw four equal width columns. Divide those columns into three equal-height rows. This is what you'll use to lay everything out.

Now, draw your labels on top of that. Notice that on the first two rows the labels occupy columns 1 and 2, and columns 3 and 4. Notice also that on the third row the label occupies columns 2 and 3.

Now, transfer that into code. Tkinter numbers rows and columns starting at zero, so the first label is row 0, column 0, and it spans two columns. Next to it is a label at row 0, column 2, and it also spans two columns.

The next row is done in the same way.

For the third row the label is row 2, column 1, and it spans 2 columns.

Don't forget to call grid_rowconfigure and grid_columnconfigure. You might want to use the uniform attribute, for example.

To make the labels perfect squares, I recommend putting each label in a frame, setting the width of the frame to whatever size you want, and then turning geometry propagation off so that the frame sets the size of the label, rather than the label setting the size of the frame. Then put the frames in the grid, instead of the labels.

You could also use a combination of the uniform and minsize options for the rows and columns, tjough you might have problems if the labels become too big to fit. Do some experimentation to see what works best for you.