Have an error when using lambda in python, do you know why?

Viewed 67

I was trying to have a checkbox which switches the value of a variable when clicked on(w/tkinter):

import tkinter as tk

CheckVar1 = tk.IntVar()
    isOn = False
    C1 = tk.Checkbutton(window, text = "Decreasing", variable = CheckVar1, onvalue=1, offvalue=0, height=5)
    C1.place(relx=0.05, rely=0.3)
    C1.bind("<<CheckboxSelect>>",lambda _: isOn = True if isOn == False else False)
    print(isOn)

But I'm having trouble with lambda:

lambda _: isOn = True if isOn == False else False

It gives an error, do you know why? How can I fix it?

1 Answers

lambdas are not supposed to have assignments, it just used for expressions and calling other functions. But there is a hacky way to assign inside of lambda. But first the correct way:

def check():
    global isOn
    if not isOn:   
        isON = True
    else:
        isOn = False

So the hacky way includes using exec to execute python code inside of lambda, like:

C1.bind("<<CheckboxSelect>>",lambda _: exec('isOn=not isOn',globals())) # Thanks to Dr. Casual for the idea
# Also recommended to use event or e or something else instead of _

So you could just change your entire check() to:

def check():
    global isOn
    isOn = not isOn
Related