1

I'm trying to develop a function which creates a new tab with many Tkinter objects (labels, buttons, spinboxes, etc.). Afterwards to assign this function to many buttons (with the button's number as the function's parameter) located in the root window. What I want to do is to rename variables inside the function's body by adding to their original names a suffix which is the function's parameter. Moreover, one of the variables is global (used as a counter).

var_1 = 0
var_2 = 0

def relay_btn(relay_number):
    var_n = 'var_' + str(relay_number)
    global var_n
    vars()[var_n] = 0 + relay_number

relay_btn(1)
relay_btn(2)

print(var_1)
print(var_2)

As a result, I'd like to see 1 and 2, respectively, not 0.

martineau
  • 119,623
  • 25
  • 170
  • 301
Stan Eskin
  • 13
  • 2
  • 2
    Creating variables on the fly is usually not a good approach. See [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – martineau Jun 16 '19 at 13:11

1 Answers1

0

When you call vars() inside the function relay_btn you are still referring to the variables within the scope of that function.

Here I return them to the global scope with return and assign the variables there.

#!/usr/bin/env python3

var_1 = 0
var_2 = 0

def relay_btn(relay_number):
        var_n = "var_" + str(relay_number)
        return var_n, relay_number

var_n, value = relay_btn(1)
vars()[var_n] = value
var_n, value = relay_btn(2)
vars()[var_n] = value

print(var_1)
print(var_2)

It's not as easy to do that all within the function with a dynamically generated variable name.. Since you can't use eval with assignments.. but i'm hoping I can convince you to find a different way to do whatever you're doing with this.. it's generally considered a bad idea. Is there a reason you can't use a data structure that is designed to store dynamically generated key value associations like a dictionary?

#!/usr/bin/env python3

d = {}

d["var_1"] = 0
d["var_2"] = 0

def relay_btn(relay_number, d):
        d["var_{}".format(relay_number)] = relay_number

relay_btn(1, d)
relay_btn(2, d)

print(d["var_1"])
print(d["var_2"])
Zhenhir
  • 1,157
  • 8
  • 13