I made entries with a loop. Now, I want to append the values (of the entries) to a dictionary that includes only the Keys. I must do it with a loop because the code would be to long if I append them one by one. I also don't really think that’s how I should reference the values of the entries in line 16.
from tkinter import *
root = Tk()
superHereos = ['Superman', 'Batman', 'Wonder Woman', 'Green Lantern', 'Flash']
Attributes = ['Name', 'Born', 'From', 'Sex', 'Hair']
Superman = {'Name': [], 'Born': [], 'From': [], 'Sex': [], 'Hair': []}
Batman = {'Name': [], 'Born': [], 'From': [], 'Sex': [], 'Hair': []}
WonderWoman = {'Name': [], 'Born': [], 'From': [], 'Sex': [], 'Hair': []}
GreenLantern = {'Name': [], 'Born': [], 'From': [], 'Sex': [], 'Hair': []}
Flash = {'Name': [], 'Born': [], 'From': [], 'Sex': [], 'Hair': []}
def appendToDict():
for i in Superman range(len(Superman)):
Superman['Name'].append(myEntry[0].get())
for entriesRow in range(len(Attributes)):
myLab = Label(root, text=superHereos[entriesRow])
myLab.grid(row=0, column=entriesRow+1)
myLab2 = Label(root, text=Attributes[entriesRow])
myLab2.grid(row=entriesRow+1, column=0)
for entriesColumn in range(len(superHereos)):
myEntry = Entry(root)
myEntry.grid(row=entriesRow+1, column=entriesColumn+1)
MyButton = Button(root, text='Click me!', command=appendToDict).grid(row=7, column=3)
root.mainloop()
Store those superhero names in a list. root.grid_slaves(row=row, column=column)
will return a list of widgets present at the row/column.
Your appendToDict
function should look something like this:
...
Flash = {'Name': [], 'Born': [], 'From': [], 'Sex': [], 'Hair': []}
superHerosLst = [Superman, Batman, WonderWoman, GreenLantern, Flash]
def appendToDict():
for heroIndex, hero in enumerate(superHerosLst, start=1):
for index, att in enumerate(Attributes, start=1):
widget = root.grid_slaves(row=index, column=heroIndex)[0]
if widget.get() != '':
hero[att].append(widget.get())
print(superHerosLst)
...
start
argument in enumerate
is 1 since all your entries start from (1, 1)
It would be better if you append your entries to a list something like this:
entriesList = []
...
for entriesColumn in range(len(superHereos)):
myEntry = Entry(root)
myEntry.grid(row=entriesRow+1, column=entriesColumn+1)
entriesList.append(myEntry)
...
for appendToDict
use this:
def appendToDict():
i, j = 0, 0
for widget in entriesList:
if j == len(superHerosLst):
j=0
i += 1
if i == len(Attributes):
i=0
att = Attributes[i]
hero = superHerosLst[j]
if widget.get() != '':
hero[att].append(widget.get())
j+=1
print(superHerosLst)