I'm playing around a bit in Tkinter python when I get this error for what I think is no reason whatsoever.
print(self.entries[x])
IndexError: list index out of range
My code:
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()
The goal is to make multiple rows of entries and submit buttons with this single loop. I have tried to remove all the self in front of everything in the function, but to no avail.
Everything works if the range() in the for loop has a 1, but not for any other number. Can someone please explain? My 1 year course in high school didn't set me up for this kind of stuff.
CodePudding user response:
You keep resetting self.entries and self.buttons each time the for loop runs. You need to move the self.entries = [] and self.buttons = [] before the for loop like this:
from tkinter import *
class Application(Frame):
def __init__(self, master):
super().__init__(master)
# self.master = master # Useless
self.submit()
def submit(self):
self.entries = []
self.buttons = []
for x in range(2):
e = Entry(self)
e.grid(row=x, column=0)
self.entries.append(e)
b = Button(self, text="SUBMIT", command=lambda x=x: print(self.entries[x].get()))
b.grid(row=x, column=1)
self.buttons.append(b)
root = Tk()
app = Application(root)
app.pack()
app.mainloop()
Also another few things:
- Instead of
self.entries[x].grid(...), you can usee.grid(...) - You never passed in anything for the
masterargument when creating the entries and buttons. - You inherited from
tk.Framebut never put anything inside it and you didn't even callapp.pack(...)/app.grid(...) - Also please you
import tkinter as tkinstead offrom tkinter import *.
CodePudding user response:
First I gave x in range(0) to solve out of index problem but buttons in output are not visible then I tried to move the self.entries = [] and self.buttons = [] before the for loop.
Code
def submit(self):
self.entries = []
self.buttons = []
for x in range(2):
