Reputation: 141
I am making four Entry widgets in tkinter using a single loop. I got an error - could anyone help me resolve the error I got in this code?
I need to track all four Entry widgets, so I created four StringVar
objects using a loop. I also have to assign separate indexes to individual Entry widgets so I used a variable 'i' in a for
loop:
from tkinter import *
class App(Frame):
def __init__(self,parent=None,**kw):
Frame.__init__(self,parent,**kw)
for i in range(4):
j=0
self.textEntryVar[i] = StringVar()
self.e[i] = Entry(self, width=15, background='white', textvariable=self.textEntryVar[i], justify=CENTER, font='-weight bold')
self.e[i].grid(padx=10, pady=5, row=17+j, column=1, sticky='W,E,N,S')
j = j+1
if __name__ == '__main__':
root = Tk()
root.geometry("200x100")
app = App(root)
Upvotes: 2
Views: 1982
Reputation: 41872
The key problem is that you index the arrays self.textEntryVar
and self.e
without ever having created them first, nor allocated any items. You need to create them as empty arrays and append onto them.
Another problem seems to be that you never pack the frame created by App()
onto the root.
Not a problem, but since you're using the Python 3 'tkiner', we might as well use the simpler Python 3 super()
initialization.
Below is my rework of your code with the above modifications and other fixes, see if it works better for you:
import tkinter as tk
class App(tk.Frame):
def __init__(self):
super().__init__()
self.pack(fill=tk.BOTH, expand=1)
self.stringVars = []
self.entries = []
for offset in range(4):
stringVar = tk.StringVar()
self.stringVars.append(stringVar)
entry = tk.Entry(self, width=15, background='white', textvariable=stringVar, justify=tk.CENTER, font='-weight bold')
entry.grid(padx=10, pady=5, row=17 + offset, column=1, sticky='W,E,N,S')
self.entries.append(entry)
if __name__ == '__main__':
root = tk.Tk()
root.geometry("200x175")
app = App()
root.mainloop()
Upvotes: 3