How to define a global variable that is created via a for loop inside another function? How to define a global variable that is created via a for loop inside another function? tkinter tkinter

How to define a global variable that is created via a for loop inside another function?


Sidestepping the fact that global variables are a Bad Idea™, here's a way to do it. Make your global variable, then don't reassign it inside the function. You can now loop over that in your button2 function. Since you want the Spinbox object, not its description, save that.

* BTW, by avoiding exec, you can severely simplify your button1 function.

spinboxes = []# Define the actions for when button one is pusheddef button1():    print "Button one pushed"    # Create the Spinboxes for each name in the list    spinbox_grid_list = []    for number, name in enumerate(names):        spinboxes.append(Spinbox(window, width=3, from_=0, to=10))        spinboxes[number].grid(padx=0, pady=0, row=13, column=number)    button_two = Button(window, text='Button two', command=button2, width=20)    button_two.grid(pady=10, padx=2, row=14, columnspan=9, sticky="S")# Define the actions for when button two is pushed (print the spinbox values)def button2():    for i, spinbox in enumerate(spinboxes):        print 'spinbox_{} = '.format(i) + (spinbox.get())

I assume that button1 is only ever called once. Otherwise, this will keep adding new spinboxes to the global list every time it's pressed. To get around that:

def button1():    print "Button one pushed"    global spinboxes    spinboxes = []    ...

We use the global keyword to let us reassign the global object, clearing it out every time the function is called.