如何访问列表中的对象?如何一次创建多个按顺序命名的对象?

2024-04-16 07:38:29 发布

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

我要一长串的检查按钮和条目。我使用for循环创建它们,但是这不允许我为对象指定唯一的名称(例如textbox1、textbox2等),因为您不能执行"foo" + char(i) = whatever。所以我创建了两个列表,一个用于复选按钮,一个用于条目。但是你如何访问列表中的对象呢?你知道吗

slot1list_check = []
slot1list_text = []

for x in range (1,21):
    label = "S1Ch. " + str(x)
    chk = Checkbutton(app, text=label).grid(row=(x+1), column=0)
    txt = Entry(app, text=label).grid(row=(x+1), column=1)
    slot1list_check.append(chk)
    slot1list_text.append(txt)
    slot1list_text[x-1].insert(0,"whatever in this field")

我得到以下错误:AttributeError:'NoneType'对象没有属性'insert',引用了上面代码中的最后一行。你知道吗

如何访问列表中的对象?有没有一种更聪明/更好的方法来创建大量对象并为它们指定顺序名称?你知道吗


Tags: 对象textin名称app列表forcheck
1条回答
网友
1楼 · 发布于 2024-04-16 07:38:29

.grid()方法在修改小部件时返回None。它不返回CheckButton()Entry()元素。你知道吗

分别调用.grid()

slot1list_check = []
slot1list_text = []

for x in range (1,21):
    label = "S1Ch. " + str(x)
    chk = Checkbutton(app, text=label)
    chk.grid(row=(x+1), column=0)
    txt = Entry(app, text=label)
    txt.grid(row=(x+1), column=1)
    slot1list_check.append(chk)
    slot1list_text.append(txt)
    slot1list_text[x-1].insert(0,"whatever in this field")

注意,我使用chktxt引用将.grid()调用移到了新行。你知道吗

您可以使用-1引用列表中的最后一个元素,因为负索引从列表末尾向后计数。在本例中,已经有了对同一对象的txt引用,因此可以直接使用它。你知道吗

就我个人而言,我只会在需要的地方使用range(20)+ 1

slot1list_check = []
slot1list_text = []

for x in range(20):
    label = "S1Ch. {}".format(x + 1)

    chk = Checkbutton(app, text=label)
    chk.grid(row=x + 2, column=0)
    slot1list_check.append(chk)

    txt = Entry(app, text=label)
    txt.grid(row=x + 2, column=1)
    txt.insert(0,"whatever in this field")
    slot1list_text.append(txt)

相关问题 更多 >