mickNeill
mickNeill

Reputation: 346

Using variable in instance name of text widget in tkinter

I am trying to use a variable in a textbox instance name in order to shuffle through them in a for loop. For example, I have 14 text widgets(infoBox1 to InfoBox14) that I am trying to fill from a list. So what I am looking to do is the following:

x=1
for item in finalList:

     self.infoBox(x).insert(END, item)

     x += 1

Then just populate the boxes as x increases. Can someone help with this?

Upvotes: 0

Views: 1145

Answers (2)

Mike - SMT
Mike - SMT

Reputation: 15226

It is possible to do what you are trying to do.

I have not come across a situation that would need to do it this way though.

Here is an example using exec to perform the commands per loop.

For more on the exec statement you can reed some documentation here

NOTE: Avoid this method and use the list/dict methods instead. This example is just to provide knowledge on how it would be possible in python.

from tkinter import *

class tester(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)       

        self.parent = parent
        self.ent0 = Entry(self.parent)
        self.ent1 = Entry(self.parent)
        self.ent2 = Entry(self.parent)
        self.ent0.pack()
        self.ent1.pack()
        self.ent2.pack()

        self.btn1 = Button(self.parent, text="Put numbers in each entry with a loop", command = self.number_loop)
        self.btn1.pack()

    def number_loop(self):
        for i in range(3):
            exec ("self.ent{}.insert(0,{})".format(i, i))


if __name__ == "__main__":
    root = Tk()
    app = tester(root)
    root.mainloop()

Upvotes: 1

Lafexlos
Lafexlos

Reputation: 7735

You don't need names to do such thing. You can put your widgets in a list then access those using indexes.

#you can create like this. Used -1 as index to access last added text widget
text_list = []
for idx in range(14):
    text_list.append(tkinter.Text(...))
    text_list[-1].grid(...)

#then you can easily select whichever you want just like accessing any item from a list

text_list[x].insert(...)
#or directly
for idx, item in enumerate(finalList):
    text_list[idx].insert("end", item)

Upvotes: 4

Related Questions