简体   繁体   中英

Multiple Entry widgets using a loop in Python tkinter

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM