简体   繁体   中英

Making a grid of Entry boxes in Tkinter in a loop

I want to make a grid of entry boxes that I can edit and save to a text file somewhere else, but every time I run my code, If I call the variable "e", I can only edit the last box that was made.

from Tkinter import *

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.TXTlist = open('txtlist.txt', 'r+')
        self.row = self.TXTlist.readline()
        self.row = self.row.rstrip('\n')
        self.row = self.row.replace('characters = ', "") #should end up being "6"
        self.columns = self.TXTlist.readline()
        self.columns = self.columns.rstrip('\n')
        self.columns = self.columns.replace('columns = ', "") #should end up being "9"
        i = 0
        x = 0
        for i in range (int(self.row)):
            for x in range (int(self.columns)):
                sroot = str('row' + str(i) + 'column' + str(x))
                e = Entry(self, width=15)
                e.grid(row = i, column = x, padx = 5, pady = 5, sticky = W)
                e.delete(0, END)
                e.insert(0, (sroot))
                x = x + 1
            x = 0
            i = i + 1
root = Tk()
root.title("Longevity")
root.geometry("450x250")
app = Application(root)
root.mainloop()

I would store the entries in some sort of data structure to have easy access to them later. a list of lists would work nicely for this:

    self.entries = []
    for i in range (int(self.row)):
        self.entries.append([])
        for x in range (int(self.columns)):
            ...
            e = Entry(self, width=15)
            self.entries[-1].append(e)
            ...

Now you have a reference to the entry box:

 self.entries[row_idx][col_idx]

And you can modify it however you want.

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