Tkinter Info Grid by loops and tuples

TrustyTony 0 Tallied Votes 2K Views Share

Here is way to put easily editable layout for input fields with standard look and collect the text variables to list for use.

from Tkinter import *

def createWidgets(root, varlist=[]):
    root.title('DaniWeb Info Grid')
    root.grid()
    font=("Calibri", 12)

    # label, place,inputplace
    info=(
        (" ",(0,0),None),
        ("First Name:",(1,1),(1,2)),
        ("Last Name:", (2,1),(2,2)),
        ("",(3,1),None),
        ("Street",(4,1),(4,2)),
        ("Zip",(5,1),(5,2)),
        ("Country",(6,1),(6,2)),
        ("",(7,1),None),
        ("Mobile",(8,1),(8,2)),
        ("Email",(9,1),(9,2)),
        (" ",(10,3),None),
        )
    
    for text,lpos,ipos in info:
        print text,lpos,ipos
        if text:
            var=StringVar()
            varlist.append(var)
            var.set('')
            
        Label(root,
              text=text,
              font=font).grid(row=lpos[0],
                              column=lpos[1])
        if ipos:
            Entry(root,
                  textvariable = var,
                  font = font).grid( row=ipos[0],
                                     column=ipos[1])
root=Tk()
vl=[]

createWidgets(root,vl)
root.mainloop()
## demonstration lines
## return through varlist, because list is mutable
for i in vl:
    print i.get()