beginner
beginner

Reputation: 21

How to control label positions and spacing in Tkinter grid

Now I want to make the food price at the same row therefore I change that to row 2 as well but then the output is this

the food goes back to row 0, why does it do that? I am trying to get something like this:

foodprice=['3','2','1.50']
drinks = ['Water','Hot water','Medium water']
drinksprice = ['1','2','3']

myFrame3 = Frame(root, bg = '')
myFrame3.pack()

myFrame3.columnconfigure(0, weight=1)
myFrame3.columnconfigure(1, weight=2)

for x in range (len(food)):
    foodop = Label(myFrame3, font=("Impact", "15"), text = food[x])
    foodop.grid(row = 2+x, column = 4) # <--
for x in range (len(foodprice)):
    fprice = Label(myFrame3, font=("Impact", "15"), text = foodprice[x])
    fprice.grid(row = 2+x, column = 8) # <--

for x in range (len(drinks)):
    drinksop = Label(myFrame3, font=("Impact", "15"), text = drinks[x])
    drinksop.grid(row = 4+(len(food))+x, column = 4) # <--
for x in range (len(drinksprice)):
    drinksp = Label(myFrame3, font=("Impact", "15"), text = drinksprice[x])
    drinksp.grid(row = 4+(len(food))+x, column = 8) # <--

Upvotes: 2

Views: 467

Answers (1)

Wolf
Wolf

Reputation: 10238

Creating white space around text does not work like in spreadsheet programs.

Tkinter collapses grid rows which are completely empty if there are no weights set by rowconfigure() to prevent this. The same is true for columns.

A layout like this:

grid layout with adjacent coordinates

import tkinter as tk

root = tk.Tk()

def place(col, row, text='Label', color='white'):
    label = tk.Label(root, text=text, bg=color)
    label.grid(column=col, row=row, 
        ipadx=10, ipady=10, padx=1, pady=1, sticky="NSEW")

def make_layout(cols, rows):

    for c in cols:
        place(c, 0, c, 'lightgrey')
        
    for r in rows:
        place(0, r, r, 'lightgrey')

    for r in rows:
        for c in cols:
            place(c, r, 'Label')

make_layout((1,2),(1,2))

root.mainloop()

... would look exactly like this:

grid layout with distant coordinates

without configuring weights in columns 8 to 29 and rows 5 to 49.

(To get this, replace make_layout((1,2),(1,2)) by make_layout((7,30),(4,50)) in code!)

And even if you added weights, Labels are still higher than weighted empty rows, and thus the layout would maybe not look as clean as you might imagine.

Tkinter's Grid Geometry Manager is a good tutorial I read the other day that goes into this detail. It also introduces the optional columnspan and rowspan parameters of the grid() function.

Last but not least, you should have a look into How to justify text in label in Tkinter

Upvotes: 1

Related Questions