0

I'm quite new to Python but especially Tkinter and I'm currently working on an app using Tkinter. I try to put a global variable inside a function. In this case, "inputcalon".

def subnocal():
    nocal_ttl.destroy()
    nocal = int(nocal_in.get())
    nocal_in.destroy()
    nocal_insub.destroy()
    for x in range(nocal):
        pesan=["Calon ", str(x+1), ": "]
        pesan="".join(pesan)
        nacal_pesan=tk.Label(text=pesan, font=z)
        nacal_pesan.pack()
        exec("global inputcalon"+str(x))
        exec("inputcalon"+str(x)+"=tk.Entry(width=10, font=z)")
        exec("inputcalon"+str(x)+".pack()")
    def register():
        for x in range(nocal):
            exec("calon.append(inputcalon"+str(x)+".get())")
    subcalon=tk.Button(text="Submit", font=z, command=register)
    subcalon.pack()

What I'm expecting is that there are global variables named "inputcalon1", "inputcalon2", etc (until it ends before x reaching nocal; nocal is another variable but that works just fine so that's not a problem).

The problem is that despite the fact that "inputcalon1", "inputcalon2" etc are declared as global variables inside function subnocal(), when I try to recall them in function register() which is inside subnocal(), those variables are not recognized. I try to put register inside the for loop but that doesn't help either. I've seen solutions like putting the global declarations inside the same function that recalls it but I need it to be outside because register() will only be triggered if you click "Submit".

What's wrong? Any help will be greatly appreciated.

Thanks.

  • I would assume each call to `exec` runs its code in a separate namespace. Note: I have never user such function, in my python life. do you really need it? – Pynchia Dec 19 '22 at 08:04
  • 1
    You are basically trying to store things using ["variable variables"](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables). Do not do this. See [this answer](https://stackoverflow.com/a/38972761/) for what you might want to be doing instead. – metatoaster Dec 19 '22 at 10:14

0 Answers0