Some very weird problem about widget dimensions in tkinter

Solution for Some very weird problem about widget dimensions in tkinter
is Given Below:

I’m trying to get the heights of some labels sorted vertically which are meant to be 690 in sum in order to see that all are equal. Well, weirdly, the numbers are incorrect while I’m using the correct codes to get and calculate them, I really don’t understand what’s the matter and why it gives much bigger number than 690 in sum. while it’s meant to be 690/6 as there are 6 labels and the height of my main window is 690…

So here is my code:

    #Modules to import

from tkinter import*
from win32api import GetSystemMetrics

#MainWindow

root = Tk()


screen_x = int(root.winfo_screenwidth())
screen_y = int(root.winfo_screenheight())  - int(root.winfo_screenheight()) * int(9.1145833333) // 100

window_x = 512
window_y = 690 

posX = (screen_x // 2) - (window_x // 2)
posY = (screen_y // 2) - (window_y // 2)

geo = "{}x{}+{}+{}". format(window_x, window_y, posX, posY)

root.geometry(geo)
root.update()

#Widgets

l1 = Label(root, text="Red Sun", bg="red", fg="white")
l1.pack(fill=BOTH, expand=True)
l1.update()
print("_______1_______")
print(l1.winfo_width(), "x", l1.winfo_height())



l2 = Label(root, text="Green Grass", bg="green", fg="black")
l2.pack(fill=BOTH, expand=True)
l2.update()
print("_______2______")
print(l2.winfo_width(), "x", l2.winfo_height())



l3 = Label(root, text="Blue Sky", bg="blue", fg="white")
l3.pack(fill=BOTH, expand=True)
l3.update()
print("______3______")
print(l3.winfo_width(), "x", l3.winfo_height())



l4 = Label(root, text="Pink Milk", bg="pink", fg="white")
l4.pack(fill=BOTH, expand=True)
l4.update()
print("_______4_______")
print(l4.winfo_width(), "x", l4.winfo_height())



l5 = Label(root, text="Orange Apple", bg="orange", fg="white")
l5.pack(fill=BOTH, expand=True)
l5.update()
print("_______5______")
print(l5.winfo_width(), "x", l5.winfo_height())



l6 = Label(root, text="White Blood", bg="white", fg="black")
l6.pack(fill=BOTH, expand=True)
l6.update()
print("______6______")
print(l6.winfo_width(), "x", l6.winfo_height())




root.mainloop()

Normally the result should be 512 x 115 for each but I keep getting this:

enter image description here

Since you have use .pack(fill=BOTH, expand=True) on those labels, so they will share all the vertical space of their parent:

  • when first label is created, its height will be 690 (fill the parent height)
  • when second label is created, the height of the two labels will be 345 each (half the parent height)
  • when third label is created, the height of the three labels will be 230 each (one-third of parent height)

So when the sixth label is created, the height of the six labels will be 115 each.