Skip to content
Advertisement

Tkinter – When adding “row=” to a Label in a for loop, items in list show up over each other

Sorry if the title is confusing I don’t really know how to word it properly. Hopefully the code below will clear it up.

When I run the program and I call print_names(), only the last name “Jenny” shows up.

While if I call the other two functions, all the items in the corresponding list show up.

However unless I add ‘row=’ then the different functions print on separate rows.

screenshot

I want to add row= so I can stop the different functions printing below each other, but if I add it, it causes only the last name to be printed.

How do I stop this from happening?

from tkinter import *
from tkinter.font import BOLD

gui = Tk()
jnames = [['Jamie','25','Male'],['John','22','Male'],['Jenny','23','Female']]

def quit():
    gui.quit()

def print_names():
    for x in jnames:
        Label(gui, text=((x[0]))).grid(column=0, row=3)

def print_ages():
    for x in jnames:
        Label(gui, text=((x[1]))).grid(column=1)

def print_gender():
    for x in jnames:
        Label(gui, text=((x[2]))).grid(column=2)

def main():
    Button(gui, text='Quit', command=quit).grid(column=1, row=0, sticky=EW)
    Button(gui, text='Print names', command=print_names).grid(column=0, row=1, sticky=EW)
    Button(gui, text='Print age', command=print_ages).grid(column=1, row=1, sticky=EW)
    Button(gui, text='Print gender', command=print_gender).grid(column=2, row=1, sticky=EW)
    Label(gui, text='Name', font=BOLD, width=15).grid(column=0, row=2, sticky=EW)
    Label(gui, text='Age', font=BOLD, width=15).grid(column=1, row=2, sticky=EW)
    Label(gui, text='Gender', font=BOLD, width=15).grid(column=2, row=2, sticky=EW)
    gui.mainloop()
main()

Advertisement

Answer

You can generate a string with all the names (or ages or genders) and then place this in the desired column and row. Here is an example:

def print_names():
    names = [x[0] for x in jnames]
    Label(gui, text='n'.join(names)).grid(column=0, row=3)

The above will simply create a multi-line string and add it to column 0 and row 3.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement