Tkinter: can widgets automatically resize to fit parent?

Michele Moore mmoore at cablespeed.com
Wed Mar 6 12:27:26 EST 2002


Eric Brunel wrote:

> Andy Gimblett wrote:
> > I want my Tk widgets (some of them, at least) to resize dynamically
> > with the window.
> >
> > Trivial example:
> >
> > #!/usr/bin/env python
> >
> > from Tkinter import *
> >
> > class Application(Frame):
> >
> >     def __init__(self, master):
> >         Frame.__init__(self, master)
> >         self.action = Button(self.master, text="Go")
> >         self.action.grid(sticky=N+E+W+S)
>
> Two reasons why it's not working:
> - you didn't actually display your Application in its master. The
> "Frame.__init__" stuff does not suffice: you should also do a pack or grid.
> Then, inserting the button in self.master rather than in self should be
> useless...
> - you configured your button to take the size of its parent cell using the
> sticky option, but you didn't tell the cell to take the whole space in its
> parent. This should be done via the grid_rowconfigure and
> grid_columnconfigure methods to set the weight option on the cell.
>
> So here is a code that does what you want:
>
> from Tkinter import *
>
> class Application(Frame):
>
>     def __init__(self, master):
>         Frame.__init__(self, master)
>         ## Actually insert self in its master
>         self.pack(fill=BOTH, expand=1)
>         ## Configure cell at (0, 0) to take the whole space
>         self.grid_rowconfigure(0, weight=1)
>         self.grid_columnconfigure(0, weight=1)
>         ## Insert button in self rather than self.master
>         self.action = Button(self, text="Go")
>         self.action.grid(sticky=N+E+W+S)
> etc...
>
> HTH
>  - eric -

And watch using both pack() and grid() to be sure
you are consistent in their usage per widget hierarchy
level. All widgets you manage on 'master' will need to
use pack() because you used pack() to manage your
Application object on it.  All the widgets managed on
the Application (Frame) need to use grid() because
you used grid() to manage the Button. Mixing pack()
and grid() at the same hierarchy level causes the application
to lock up and unless you've experienced this first hand, it
may be difficult to debug.




More information about the Python-list mailing list