Home > Software design >  Tkinter: Global in function does not seem to work on button click
Tkinter: Global in function does not seem to work on button click

Time:08-11

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.

CodePudding user response:

Edit: I put this print inside the value function in line 6.

Try this:

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()

 
root.mainloop()

CodePudding user response:

I found a way using lambada 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]

  • Related