Home > Software design >  Grouping Tkinter entry widgets and creating a for loop
Grouping Tkinter entry widgets and creating a for loop

Time:12-24

I'm new to Tkinter and just wondering if there is anyway I could group some entry boxes like in a list and then do a for loop on them.

I'm watching this tutorial video and on clicking a button they want the button to clear all the entry boxes and they've done it like this:

# Create Submit fn for database
def submit():
    f_name.delete(0, END)
    l_name.delete(0, END)
    address.delete(0, END)
    city.delete(0, END)
    postcode.delete(0, END)

# Create entry textboxes
f_name = ttk.Entry(mainframe, width=30).grid(column=1, row=0)
l_name = ttk.Entry(mainframe, width=30).grid(column=1, row=1)
address = ttk.Entry(mainframe, width=30).grid(column=1, row=2)
city = ttk.Entry(mainframe, width=30).grid(column=1, row=3)
postcode = ttk.Entry(mainframe, width=30).grid(column=1, row=4)

# Create submit button
submit_btn = ttk.Button(mainframe, text="Add Record", width=20, command=submit).grid(column=0, row=6, pady=10)

Instead of the submit function being repetitive I would like to do something like this:

def submit():

entries = ttk.Entry(mainframe)

for entry in entries:
    entry.delete(0, END)

That function immediately above doesn't work but I'm looking for something along those lines to avoid the unneccessary repetition and have cleaner code. Is this possible?

CodePudding user response:

Widgets are objects, and objects can be added to a list. You do it no differently than you do strings or integers or any other type of object.

f_name = ttk.Entry(mainframe, width=30)
l_name = ttk.Entry(mainframe, width=30)
address = ttk.Entry(mainframe, width=30)
city = ttk.Entry(mainframe, width=30)
postcode = ttk.Entry(mainframe, width=30)

f_name.grid(column=1, row=0)
l_name.grid(column=1, row=1)
address.grid(column=1, row=2)
city.grid(column=1, row=3)
postcode.grid(column=1, row=4)

entries = [f_name, l_name, address, city, postcode]
...
for entry in entries:
    entry.delete(0, END)

You can also use a dictionary instead of individual variables. You can then iterate over the dictionary like you do any other dictionary:

entries = {
    "f_name": ttk.Entry(...),
    "l_name": ttk.Entry(....),
    ...
}
  • Related