Eduardo
Eduardo

Reputation: 1265

Tkinter grid problems

Shouldn't the "One Label" expand to occupy the full width (minus the padding) of the column? It doesn't for me (OS X 10.9.5); it always appears justified left and occupying its natural width:

from Tkinter import *

root = Tk()
root.configure(background='black')

frame = Frame(root, bg='red', takefocus=0)
frame.pack()

l0 = Frame(frame, bg='blue')
l0.grid(row=0, sticky=W+E)
l0x=Label(l0,text='One Label', takefocus=1)
l0x.grid(padx=2, pady=2, sticky=W+E)

l1 = Frame(frame, bg='yellow')
l1.grid(row=1, sticky=W+E)
l1x=Label(l1,text='Another Label', takefocus=1)
l1x.grid(padx=2, pady=(0,2), sticky=W+E)

root.mainloop()

Upvotes: 0

Views: 128

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385940

Yes, the label does fit the full width of the column. The problem is that the column doesn't fit the whole width of the containing frame.

By default, the grid geometry manager leaves any extra space unused. More precisely, it allocates extra space to every row and every column with a positive weight. By default, rows and columns have a weight of zero, so extra space is left un-allocated.

A quick fix is to make sure that column zero of each inner frame has a non-zero weight:

l0.grid_columnconfigure(0, weight=1)
l1.grid_columnconfigure(0, weight=1)

There are similar issues with all of your frames, but the solution is the same in every case where you use grid.

As a general rule of thumb, in any given container (typically a Frame, or the root window), at least one row and column needs to have a weight of 1.

Upvotes: 1

Related Questions