Search code examples
python-3.xtkinterlabeltkinter-entry

can I automatically define tkinter widgets using a loop?


In the next code categories is a list. The code makes a window and adds labels and entry for each item on the list.

class Win3():
                def __init__(self, master, categories):
                                self.master = master
                                self.master.geometry('400x250')
                                self.master.resizable(False,False)
                                self.frame = Frame(self.master)
                                self.frame.grid(row=0, column=0, sticky=NW)
                                y=0
                                for x in categories:
                                                Label(self.frame, bg='#92DBE9' ,width=15 ,text=x).grid(row=y,column=0,padx=2,pady=2)
                                                Entry(self.frame, bd=1, width = 20).grid(row=y,column=2, padx=2,pady=2)
                                                y+=1

How can I define the labels so I can define the labels and entries like label1, entry1 label2, entry2,... I want to use this so I can still change the text from the label or the insert after creating them.


Solution

  • You don't need to "define the labels and entries like label1, entry1 label2, entry2". The names are irrelevant. You can save them as elements in a dictionary or list.

    labels = []
    entries = []
    for x in categories:
        label = Label(self.frame, bg='#92DBE9' ,width=15 ,text=x)
        entry = Entry(self.frame, bd=1, width = 20)
    
        label.grid(row=y,column=0,padx=2,pady=2)
        entry.grid(row=y,column=2, padx=2,pady=2)
    
        labels.append(label)
        entries.append(entry)
    
        y+=1
    

    With that, you can now access the labels with something like labels[0], labels[1], and so on. Likewise with the entries.