Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
<pre><code>from tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()
        self.plot = Canvas(master, width=500, height=120)
        self.plot.pack()

        self.1 = self.plot.create_text(10,10, text = "0")
        self.2 = self.plot.create_text(30,10, text = "0")
        self.3 = self.plot.create_text(50,10, text = "0")

        def txt_change(self,name,value):
            self.plot.itemconfigure(self.name, text=value)
</code></pre>

<p>So here I want to create just 1 function that can change the value of multiple variables by including a name. This name is however a string,but I want python to interpret the string as a variable name. I have 20 variables like this, and creating a new function for every variable doesn't look very clean. Is there a smart way to do this?</p>

<p>I was hoping that in the end I could use something like this: txt_change("1",20)</p>

<p>The proper solution isn't to translate strings to variable names. Instead, store the items in a list or dictionary.</p>

<p>For example, this uses a dictionary:</p>

<pre><code>class App:
    def __init__(self, master):
        ...
        self.items = {}
        self.items[1] = self.plot.create_text(10,10, text = "0")
        self.items[2] = self.plot.create_text(30,10, text = "0")
        self.items[3] = self.plot.create_text(50,10, text = "0")

    def txt_change(self,name,value):
        item_id = self.items[name]
        self.plot.itemconfigure(item_id, text=value)

...
app=App(...)
app.txt_change(2, "this is the new text")
</code></pre>

python string variables tkinter tkinter-canvas