【发布时间】:2021-09-15 10:57:01
【问题描述】:
当我因为我认为没有任何原因而收到此错误时,我在 Tkinter python 中玩了一下。
print(self.entries[x])
IndexError: list index out of range
我的代码:
from tkinter import *
class Application(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.submit()
def submit(self):
for x in range(2):
self.entries = []
self.buttons = []
e = Entry()
self.entries.append(e)
self.entries[x].grid(row=x, column=0)
b = Button(text='SUBMIT', command=lambda x=x: print(self.entries[x].get()))
self.buttons.append(b)
self.buttons[x].grid(row=x, column=1)
root = Tk()
app = Application(root)
app.mainloop()
我们的目标是通过这个单一循环创建多行条目并提交按钮。我已经尝试删除函数中所有内容前面的所有自我,但无济于事。
如果 for 循环中的 range() 为 1,则一切正常,但对于任何其他数字均无效。有人可以解释一下吗?我高中的 1 年课程并没有让我适应这种东西。
【问题讨论】:
-
将
self.entries = []和self.buttons = []移到for循环之前 -
也可以用
e.grid(...)代替self.entries[x].grid(...),同样前self.buttons[x].grid(...)
标签: python-3.x tkinter