What does return mean?

Asked 2 years ago, Updated 2 years ago, 122 views

Program 1.

def make_cmd(i):
  return lambda:buff.set("button{}pressed".format(i))

button=Tkinter.Button(root, text="Button{}".format(i), command=make_cmd(i))

Program 2.

def make_cmd(i):
  return buffer.set("button{}pressed".format(i))

button=Tkinter.Button(root, text="Button{}".format(i), command=make_cmd(i))

In the case of 1, it works well, but in the case of 2, an error occurs when substituting button.
The return value for 1 was <function<lambda>at0xb714adbc>, where 2 was none.
Why is 2 none?

python tkinter

2022-09-30 21:14

2 Answers

Why does 2 become none?

This is because the buff.set() function returns None.

The point of this program is the value passed to the command argument in TKinter.Button.
The command argument expects a function object.
For example, some implementation samples work.

def callback():
    print "click!"

b=Button(master, text="OK", command=callback)

Now, if you look at the implementation of Program 1, you're using lambda.

def make_cmd(i):
    return lambda:buff.set("button{}pressed".format(i))

Implementing this without lambda would look like this:

def make_cmd(i):
    defcmd():
        buff.set("button{}pressed".format(i))
    return cmd

Note that the make_cmd function returns the cmd function, which is passed to the command argument in TKinter.Button.buff.set is not passed to the command argument.
In this example, we define an in-function function called cmd, which is written briefly inline using lambda in program 1.Lambda also allows you to pass directly to TKinter.Button without defining the make_cmd function.

 button=Tkinter.Button(
             root,
             text = "Button{}".format(i),
             command=lambda:buff.set("button{}pressed".format(i))
         )


2022-09-30 21:14

To put it very simply, the following is true:

Program 1 returns the lambda formula itself, the processing function when a button is pressed.The contents of the function are not executed at this time.Runs when the button is pressed.

Program 2 returns the results of buf.set(), but it actually returns nothing, so it becomes none.buf.set() is running at this point.


2022-09-30 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.