Home > other >  Global prefix not setting variable
Global prefix not setting variable

Time:11-30

I'm trying to make a Tkinter window that sets a variable to something depending on which button you clicked. From what I know the only way to do this is to make "command" assigned to a function. but the code that uses the variable isn't in that function, so I'm trying to use "global" to set the actual variable I want to the choice. But for some reason, it still returns 0 which is what I originally set it to. Here is my code

        choi = 0
        def return1():
            global choi
            choi = '1'
            print(choi)
        def choicedone():
            choiwind.destroy()
        choiwind = tkinter.Tk()
        preset1_button = tkinter.Button(choiwind, text = 'button', command = return1)
        quit_button = tkinter.Button(choiwind, text = 'Done', command = choicedone)
        preset1_button.pack()
        quit_button.pack()
        choiwind.mainloop()
        print(choi)
        if choi == '1':
            #do stuff
        else:
            print('Error')

It returns "1" then "0" then "Error"

CodePudding user response:

Look like the posted code is inside a function, so global choi does not refer the choi variable inside that function.

You need to change global choi to nonlocal choi.

Refer the Python document on global and nonlocal for details.

  • Related