Search code examples
pythongridtkinterframes

tkinter: grid method strange behavior


I want this code to do this:

Create 4 frames with this layout (dashes mean the frame spans that column):

 -X-
 XXX

Within each of these frames (X's) there should be two rows like this:

cowN,1
cowN,2

It seems like the grid() method is global ONLY and is never specific to a single frame...

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

master = Tk()

frame1 = Frame(master).grid(row=0,columnspan=3)
frame2 = Frame(master).grid(row=1,column=0)
frame3 = Frame(master).grid(row=1,column=1)
frame4 = Frame(master).grid(row=1,column=2)
#->Frame1 contents
Label(frame1, text='cow1,1').grid(row=0)
Label(frame1, text='cow1,2').grid(row=1)
#->Frame2 contents
Label(frame2, text='cow2,1').grid(row=0)
Label(frame2, text='cow2,2').grid(row=1)
#->Frame3 contents
Label(frame3, text='cow3,1').grid(row=0)
Label(frame3, text='cow3,2').grid(row=1)
#->Frame4 contents
Label(frame4, text='cow4,1').grid(row=0)
Label(frame4, text='cow4,2').grid(row=1)

master.mainloop()

Solution

  • The problem with your code is that your are not keeping a reference to the Frame objects on your frameN variables: you create the objects, and call their grid method: you store the return of the grid method on the variables, which is None.

    So, your labels are being created with None as their master.

    Just change your lines to read:

    frame1 = Frame(master); 
    frame1.grid(row=0, columnspan=3)