我用循环输入。现在,我想将(条目的)值附加到仅包含键的字典中。我必须用循环来完成,因为如果我将它们一一附加,代码会很长。我也不认为这就是我应该如何引用第 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()
答案 0 :(得分:1)
将这些超级英雄的名字存储在一个列表中。 root.grid_slaves(row=row, column=column)
将返回存在于行/列的小部件列表。
您的 appendToDict
函数应如下所示:
...
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
中的 enumerate
参数为 1,因为您的所有条目都从 (1, 1) 开始
如果您将条目附加到如下列表中会更好:
entriesList = []
...
for entriesColumn in range(len(superHereos)):
myEntry = Entry(root)
myEntry.grid(row=entriesRow+1, column=entriesColumn+1)
entriesList.append(myEntry)
...
对于 appendToDict
使用这个:
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)