问题
I just started with my first Python program and ran into a pretty strange issue with function callback. Here is the code that matches my expectation:
from tkinter import *
def say_hello():
print('hello')
root = Tk()
Button(root, text='say hello', command=say_hello).pack()
root.mainloop()
Now if I add parentheses to the function name
Button(root, text='say hello', command=say_hello()).pack()
'hello' will be printed only once when the program starts, but nothing further happens when the button is clicked. Why?
Thanks!
回答1:
When you add parentheses, you call the function (immediately printing "hello"), and its return value (not the function itself) is used as the callback.
The return value of None
is a valid callback, indicating that there is no callback function for the Button
. If say_hello
returned, say, an int
, you will probably get an error when you click the button to the effect that an int
is not a callable value.
回答2:
say_hello
is function. In 1st case you're providing it as argument, saying "Here's button, her's function say_hello
. Execute (call) this function when you're pressed".
2nd case — if you're writing parentheses after function, this is the function call. So you're not providing your button with something to call later, but giving raw value instead.
The idea of callbacks overall — you provide something callable (function say_hello
in your case) to object (Button
in your case), so that object can call back in future, when it decides to do so (in your case, when pressed)
来源:https://stackoverflow.com/questions/54421018/function-callback-in-event-binding-w-and-w-o-parentheses