Home > Software design >  Creating and using a large number of objects with a non-preset name in Tkinter, Python
Creating and using a large number of objects with a non-preset name in Tkinter, Python

Time:05-27

What I`m using: Tkinter lib, setattr() function

What I want: by using a for loop create some number of widgets with some parameters and roughly similar names. Then, I want to be able to set their location using the same loop

How it looks for me for now:

class Window(Tk):
    def __init__(self):
    Tk.__init__(self)
    for i in range(n):
        setattr(Label(self, text=f"name{i}", OTHER_OPTIONS), f"name{i}", _value)
        name{i}.place(y=0 10*i)

What I expect to see: a column of text from name0 to nameN with 10 units between each

For what I need it?: to create a function in which I can send parameters like name of object, text, background and other of label options

Thanks in advance for the answer!

CodePudding user response:

You're making this more difficult than it needs to be. Just store the labels in a list or dictionary.

self.labels = []
for i in range(n):
    label = Label(self, ...)
    self.labels.append(label)

I also strongly recommend against place. It's much easier to create responsive applications using pack and grid. With place you have to a lot more work, and it's easy to create a UI that looks good only looks good for one specific configuration (resolution, default font, window size).

  • Related