so i'm making a project for a buddy that's going to (eventually) ask a word, then it's definition, and I need 50 entry boxes on the screen, but there must be a simpler way to grid all of them (I'd like to use a sort of for loop instead of having to define them all).

from Tkinter import *
import time
import tkSimpleDialog
import tkMessageBox
import random

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        Label(self, text="Root Word").grid(row=0, column = 1)
        Label(self, text="Definition").grid(row=0, column = 2)
        Label(self, text="Example").grid(row=0, column = 3)
        #self.i = 2
        for self.i in  range(25):
            Label(self, text=str(1+(self.i))).grid(row=int(1+(self.i)), column = 0)
            self.i = self.i + 1


        for i in range(25):
            setattr(self, 'a'+str(i), Entry(self))
            i = i + 1

        #### FIND A WAY TO GRID ALL ENTRY BOXES HERE ####

root = Tk()
root.title("English")
root.geometry("1000x1000")
app = Application(root)
root.mainloop()

You should really use a list of entry boxes.
Something like this:

''' tk_entry_loop2.py
exploring Tkinter multiple labeled entry widgets
and using a for loop to create the widgets
'''

from functools import partial
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

class Gui(tk.Tk):
    def __init__(self):
        # the root will be self
        tk.Tk.__init__(self)
        self.title('multiple labeled entries')

        self.entries = []
        for n in range(20):
            # create left side info labels
            tk.Label(self, text="%2d: " % n).grid(row=n, column=0)
            # create entries list
            self.entries.append(tk.Entry(self, bg='yellow', width=40))
            # grid layout the entries
            self.entries[n].grid(row=n, column=1)
            # bind the entries return key pressed to an action
            self.entries[n].bind('<Return>', partial(self.action, n))

        # test, load one entry
        self.entries[0].insert('end', 'enter a word in an entry')

    def action(self, ix, event):
        '''this entry return key pressed'''
        text = self.entries[ix].get()
        info = "entry ix=%d text=%s" % (ix, text)
        # use first entry to show test results
        # clear old text
        self.entries[0].delete(0, 'end')
        # insert new text
        self.entries[0].insert('end', info)

    def run(self):
        self.mainloop()


# test the potential module
if __name__ == '__main__':
    Gui().run()

Edited 3 Years Ago by Lardmeister

This article has been dead for over six months. Start a new discussion instead.