Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretching frames using grid layout in Python Tkinter

I'm trying to get stretching to work using Python 2.6.7 with Tkinter. I'd expect the below code to stretch the first button to the width of the second, but both buttons are only as wide as they need to be to fit their text.

#!/usr/bin/python
from Tkinter import *

win = Frame()
win.grid(sticky=N+S+E+W)

inner_a = Frame(win)
inner_a.grid(row=0, column=0, sticky=N+E+W)
inner_b = Frame(win)
inner_b.grid(row=1, column=0, sticky=S+E+W)

Button(inner_a, text='1').grid(row=0, column=0, sticky=E+W)
Button(inner_b, text='Some long text').grid(row=0, column=0, sticky=E+W)

win.mainloop()

By my understanding, the single column in win will expand to the width of the largest thing it contains, ie the width of inner_b, and then the width of inner_a, and thence of the first button, will be that of the second button.

Actually, what happens is the below; the first button is only wide enough to contain "1", not as wide as the second button.

Screen shot: two buttons stacked on top of each other, the first has the single character "1", the second the words "Some long text". The bottom button is considerably wider than the top.

What do I need to do to get the first button to expand the size of the second?

like image 615
me_and Avatar asked Mar 15 '12 21:03

me_and


1 Answers

If you want widgets to line up in a grid, the first thing to do is make sure they have the same parent. This isn't strictly necessary if all the widgets are the same size or you are only using one column.

Another thing you need to do is give your column a weight. What is happening in your code is that the widget is expanding to fill the column, but the column isn't expanding to fill the master. If you give it a weight of 1 it will. You ned to do something like inner_a.columnconfigure(1, weight=1), and then do likewise for inner_b.

like image 90
Bryan Oakley Avatar answered Oct 23 '22 10:10

Bryan Oakley