在PythonTkinter中,如何使用for循环将空字典的条目值追加?

2024-10-04 11:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我用循环输入。现在,我想将(条目的)值附加到只包含键的字典中。我必须用一个循环来完成,因为如果我一个接一个地附加它们,代码会很长。我也不认为我应该这样引用第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()

Tags: nameinfromforcolumnrootattributesgrid
1条回答
网友
1楼 · 发布于 2024-10-04 11:35:37

将那些超级英雄的名字储存在一个列表中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)

...

enumerate中的start参数是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)

相关问题 更多 >