[Tutor] laying out frames

Michael Lange klappnase at freenet.de
Mon May 15 23:54:51 CEST 2006


On Mon, 15 May 2006 15:42:48 -0400 (EDT)
"Zubin Wadia" <zubinw at zapdomain.ca> wrote:

> Hello Everyone,
> 
> Another basic question in regard to frame layouts with Tkinter.
> 
> I want to create a basic quadrant of frames but am not able to follow the
> logic to do so, whats the right way or an easier way to control layout of
> frames and wigets. A pixel approach would be nice (where by you can
> specify pixel locations for a frame or a widget to be located) instead of
> specifying arbitary location positions like LEFT, RIGHT, etc and things
> moving constantly when you add more widgets or resize windows.
> 

Hi Zubin,

there are three different geometry managers in Tkinter, pack(), grid() and place().
As you have noticed, pack() is very handy to use for simple gui layouts but more complex
ones may be hard to achieve.
grid() is more flexible than pack(), it lets you arrange widgets in row and columns, e.g.:

from Tkinter import *
root = Tk()
# define rows and columns that should expand on window resizing
root.grid_rowconfigure(1, weight=1)
root.grid_rowconfigure(2, weight=1)
root.grid_columnconfigure(0, weight=1)
Label(root, text='Label1', bg='white').grid(row=0, column=0, sticky='ew')
Label(root, text='Label2', bg='yellow').grid(row=0, column=1)
Label(root, text='Label3', bg='green').grid(row=0, column=2)
Label(root, text='Label4', bg='red').grid(row=1, column=0, columnspan=2, sticky='nsew')
Label(root, text='Label5', bg='blue').grid(row=2, column=0, columnspan=3, sticky='nsew')
root.mainloop()

place() is even much more flexible than grid(), but it is much more complex to use, too,
so I recommend to think twice if you really need its capabilities.
With place() you can define absolute or relative x ynd y coords of a widget in its container and
relative or absolute dimensions, e.g:

from Tkinter import *
root = Tk()
Label(root, text='Label1', bg='green').place(x=10, y=40, relwidth=0.5, relheight=0.3)
Label(root, text='Label2', bg='yellow').place(relx=0.1, rely=0.8, width=60, height=30)
root.mainloop()

I hope this helps

Michael


More information about the Tutor mailing list