Making Gridded Widgets Expandable

Hamilton, William whamil1 at entergy.com
Mon Jul 30 16:24:04 CEST 2007


> From: Jim
> Hi,
> I'm looking at page 548 of Programming Python (3rd Edition) by Mark
> Lutz.
> The following GUI script works with no problem, i.e., the rows and
> columns expand:
> =================================================================
> # Gridded Widgets Expandable page 548
> 
> from Tkinter import *
> colors = ["red", "white", "blue"]
> 
> def gridbox(root):
>     Label(root, text = 'Grid').grid(columnspan = 2)
>     r = 1
>     for c in colors:
>         l = Label(root, text=c, relief=RIDGE, width=25)
>         e = Entry(root, bg=c,   relief=SUNKEN, width=50)
>         l.grid(row=r, column=0, sticky=NSEW)
>         e.grid(row=r, column=1, sticky=NSEW)
>         root.rowconfigure(r, weight=1)
>         r += 1
>     root.columnconfigure(0, weight=1)
>     root.columnconfigure(1, weight=1)
> 
> root = Tk()
> gridbox(Toplevel(root))
> Button(root, text="Quit", command=root.quit).grid()
> mainloop()
> =================================================================
> However, the following GUI script using class does not expand rows and
> columns:
> =================================================================
> # Gridded Widgets Expandable 2
> 
> from Tkinter import *
> colors = ["red", "white", "blue"]
> 
> class GUI(Frame):
>     def __init__(self,master):
>         Frame.__init__(self,master)
>         self.grid()
>         self.gridbox()
> 
>     def gridbox(self):
>         Label(self, text = 'Grid').grid(columnspan = 2)
>         r = 1
>         for c in colors:
>             l = Label(self, text=c, relief=RIDGE, width=25)
>             e = Entry(self, bg=c,   relief=SUNKEN, width=50)
>             l.grid(row=r, column=0, sticky=NSEW)
>             e.grid(row=r, column=1, sticky=NSEW)
>             self.rowconfigure(r, weight=1)
>             r += 1
>         self.columnconfigure(0, weight=1)
>         self.columnconfigure(1, weight=1)
> 
> root = Tk()
> root.title("Gridded Widgets Expandable")
> app = GUI(root)
> Button(root, text="Quit", command=root.quit).grid()
> root.mainloop()
> =================================================================
> What am I missing?


In the first, your gridbox has Toplevel(root) as its master, causing it
to be created in a new window.  In the second, it has Frame(root) as its
master, which does not create a new window.  Changing Frame to Toplevel
in the class statement and the call to __init__ causes them to act
identically.


--
-Bill Hamilton



More information about the Python-list mailing list