Search code examples
pythontkinterglobaltkinter-button

Tkinter: Global in function does not seem to work on button click


I want the var state to be True after clicking the button.

This is the code

from tkinter import *
root = Tk()
def value():
        global state
        state = True
        print(state)

btn_choose_mouse_position = Button(root, text=' Choose click positions', fg='black', bg="green",
                                   activebackground='#6D8573', command=value, padx=20, pady=20).pack()

try: print(state)

except:
    pass
try:
    if state:
        print('works')
except:
    pass
root.mainloop()

When I click the button, only True from the function is printed.


Solution

  • I found a way using lambda to set the var state to True

    from tkinter import *
    root=Tk()
    state = BooleanVar()
    btn_choose_mouse_position = Button(root, text=' Choose click positions', fg='black', bg="green",
                                       activebackground='#6D8573', command=lambda : state.set(True), padx=20, pady=20)
    btn_choose_mouse_position.pack()
    
    btn_choose_mouse_position.wait_variable(state)
    root.mainloop()
    

    state = BooleanVar() makes state a bool without a True or False

    .wait_variable(state) waits for bool to change, a bit like os.wait

    [enter link description here]