Indirectly reference objects using a string

I am struggling to indirectly reference objects using anvil.

Suppose I had 10 images labelled Image0 to Image9 respectively, how would I reference them without listing each individual name?

I would like something like this:

for i in range(10):
    name = "Image"+str(i)
    self.name.source = "Image"

Instead of:

self.Image0.source = "Image"
self.Image1.source = "Image"
    ...
self.Image9.source = "Image"

Thanks,
Charlie

I believe using the “tag” property would help “name” a component. You can place your components into a list so you can iterate through them. You also place them into an Anvil container and iterate through them similarly (e.g., with self.column_panel.get_components())

Here are some posts that might help:

2 Likes

In this case you could use a list to refer to images, if you create your images in code then:

self.images = [Image(source="Image") for image in range(10)]

self.images[0].source = "New Image source"

Or if you use the design template to create your images then you’ll have to write them by hand first…

self.images = [self.image0, self.image1, self.image2, ..., self.image9]
for image in self.images:
  image.source = "Image"

Or…if you don’t fancy that

self.images = []
for component_name in dir(self):
    if "image" in component_name:
        self.images.append(getattr(self, component_name))

And if you have a different naming convention

self.images = []
for component_name in dir(self):
    component = getattr(self, component_name)
    if isinstance(component, Image):
        self.images.append(component)

3 Likes