Pergunta

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

Foi útil?

Solução

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.

Outras dicas

Assume you have 5 buttons (Label or anything else):

import tkinter as tk

master = tk.Tk()
master.title('Test')
master.geometry("100x100+700+350")

b1 = tk.Button(text='1')
b1.grid(row=0, column=0)

b2 = tk.Button(text='2')
b2.grid(row=0, column=1)

b3 = tk.Button(text='3')
b3.grid(row=1, column=0)

b4 = tk.Button(text='4')
b4.grid(row=1, column=1)

b5 = tk.Button(text='5')
b5.grid(row=2, columnspan=2)

tk.mainloop()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top