0

i am trying to figure out a problem i'm having with declaring a variable upon a button click. For instance i wish to assign to the variable f the value True. I seem to be having trouble with the syntax or method of using the Button function to declare the variable. Do i initialize the variable beforehand? im not quite sure

here is my code:

import tkinter
from tkinter import *
root=Tk()
b1=Button(root,text="test", command=lambda: f=True)
b1.pack()
root.mainloop()

1 Answer 1

1

In Python, assignment is a statement, and thus cannot be done with simple lambdas, which can only contain expressions (function calls, variables, attributes, ... not statements, returns1, breaks, ...). To do what you're wanting to do, you must define a normal function as so:

f = False

def onclick():
    global f
    f = True

This will access the global namescape's f, (use nonlocal if you're within another function) and use that variable within the function. By assigning to this you will change its value in the outer scope.

Note that you must have f defined in the outer scope before the function can reassign it.

To use it, set the command to onclick as such:

b1=Button(root,text="test", command=onclick)

A lambda isn't necessary as you're passing the function object

Note that the function definition must occur before it is passed as the command argument to the new Button

1: By this I mean returning from an outer function, not returns within the lambda, as the entire lambda expression itself is returned.

Sign up to request clarification or add additional context in comments.

1 Comment

hello! I have a similar issue: could I ask you in private chat? @Annonymous

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.