The following program does not behave exactly as I expect. I expect the left and right edges of the blue label to exactly match the left edge of the red label and the right edge of the green label, respectively. Instead, the blue label is slightly smaller than that:
from tkinter import *
window = Tk()
r = Label(bg="red", width=20, height=5)
r.grid(row=0, column=0)
g = Label(bg="green", width=20, height=5)
g.grid(row=1, column=1)
b = Label(bg="blue", width=40, height=5)
b.grid(row=2, column=0, columnspan=2)
window.mainloop()
The image I get is the following:
I tried this both on Mac and on Windows, with the same result.
What is going on here? And how can I fix the blue label to exactly match the other labels?
I tried changing the width of the blue label to 41, but that made it slightly too big.
If you print out the configurations of a label using
.config()
, you will find that theborderwidth
is 2 pixels andpadx
is 1 pixel and the width of a 20 characters label with default font using.winfo_width()
is 140 pixels (in my Windows 11 with Python 3.12.0). A 40 characters label is 280 pixelsSo the total width of two 20 characters label is
(2+1+140+1+2)*2 = 146*2 = 292
pixels and the width of a 40 characters label is2+1+280+1+2 = 286
.So the result is expected. You can set the
borderwidth
andpadx
to 0 for all the labels and then you will get what you want.Or you can set
sticky="ew"
tob.grid(...)
so that the blue label will be expanded to fill the horizontal space.