Python, change a var by a string

I have multiple type1 = Label(image=type_none) and get a list ['Ground', 'Rock', 'Water'] and want to change it to

type1 = Label(image=type_Ground)

type2 = Label(image=type_Rock)

etc. The type_Rock are already defined, and contain Data i want to Display.

So i am looking for a way to dynamically change the Variable. Something like this.

for i in range(0, len(type_list)):
    type{i} = Label(image=type_{type_list[i]})

In the end it should update the Images of the Labels 1 through X. I am still a beginner and cant find a way to do this. I would post the full code, but it is large and messy. In case you need to know, the Image i have to define as self.type_ground = ImageTk.PhotoImage("img/Ground.png").resize(self.type_size))
Thanks for your time reading through my Problems 🙂

Edit: Thanks for the Answers, i initially looked at eval(), and it worked fine, but i ran into some issues and because you all said it was bad practices, i now use dicts and lists containing the Variables.

The Image can be easily created like so: type_img = {"Scaning": ImageTk.PhotoImage("img/Scaning.png").resize(type_size))},

but the Tk.Label objects, i needed to handle different.
First i create the Label wtype0 = Label(master, image=type_img["None"]), place it in Tkinter, then store it in a list type_tklist = [self.wtype0]

Then when i want to change the images, i can simply

for i in range(0, len(weak1)):
     self.type_tklist[i].image = self.type_img[weak1[i]]

Stack Overflow Asked by Beardlongo on February 21, 2021

4 Answers

4 Answers

This is possible...

This is possible, using the built-in function eval, but it is almost always a very bad idea. Regardless, if you'd want to do this, you could do something like:

for i in range(0, len(type_list)):
    eval('type{} = something'.format(i))

But there are always better options

Instead, consider using a list of types:

types = []
for i in range(0, len(type_list)):

which you can then access like types[1].

If you want better "names" for the different types than just numbers, consider using a dict.

Correct answer by ADdV on February 21, 2021

If I'm understanding your question correctly, there are a couple of routes to choose in my mind: one using classes and the other using a dictionary. For speed, I will show the method with a dictionary with an enumeration method to get by having to fiddle too much with indices.

data = {}
names = ["Ground", "Rock", "Water"]

for i, type in enumerate(type_list):
   key = names[i] 
   data[key] = Label(image=type)

From here, you can choose the data you want to work with by simply keying the name of the type you're interested in; for instance:

# type1
type1 = data["Ground"]

Please let me know if I misunderstood.

Answered by Liquid Snake on February 21, 2021

This is technically possible using Python's eval() function, but it's considered bad programming practice.

Instead of defining your images as type_Rock, type_Ground, I'd recommend creating a dictionary type_images where your key is Rock, Ground, etc.

Your loop would look like:

for t, img in type_images.items():
    type{i} = Label(image=img)

Answered by jpear1 on February 21, 2021

you can create string and then use eval()

ex :

    eval(f"type{i} = Label(image=type_{type_list[i]})")

Answered by SeYeD.Dev on February 21, 2021

Add your own answers!

Related Questions

Find a cell containing a specific date

1  Asked on December 22, 2021


Jeykll file to import not found or unreadable: base

1  Asked on December 22, 2021 by kyu96


Unable to remove event listener from document

1  Asked on December 22, 2021 by prawn


Invalid result adding the number of 1s in a binary number

2  Asked on December 20, 2021 by aworeham


How to print the elements of 3 different arrays by the order?

2  Asked on December 20, 2021 by fuzzyfiso


Finding string elements of an array in another array

5  Asked on December 20, 2021 by p-emt


How to plot several columns on the same line chart in R?

2  Asked on December 20, 2021 by user13953317


Is there a way to craft URLs to fill forms faster?

1  Asked on December 20, 2021 by rosalind-goh


infinite loop while using useEffect and redux store

0  Asked on December 20, 2021 by susanta


Cannot convert textfield into string

1  Asked on December 20, 2021 by anuj-amin


Is there multiple ways to cin vector elements?

1  Asked on December 20, 2021 by 2kbummer


Ask a Question

Get help from others!

© 2022 All rights reserved.