事件绑定中的函数回调,带和不带括号 [英] Function callback in event binding, w/ and w/o parentheses

查看:31
本文介绍了事件绑定中的函数回调,带和不带括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用我的第一个 Python 程序,遇到了一个非常奇怪的函数回调问题.这是符合我期望的代码:

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' 只会在程序启动时打印一次,但在单击按钮时不会再发生任何事情.为什么?

'hello' will be printed only once when the program starts, but nothing further happens when the button is clicked. Why?

谢谢!

推荐答案

当你添加括号时,你调用函数(立即打印hello")及其返回值(不是函数本身)) 用作回调.

When you add parentheses, you call the function (immediately printing "hello"), and its return value (not the function itself) is used as the callback.

None 的返回值是一个有效的回调,表示没有Button 的回调函数.如果 say_hello 返回,比如说,一个 int,当你点击按钮时,你可能会得到一个错误,即 int 不是一个可调用的价值.

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.

这篇关于事件绑定中的函数回调,带和不带括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆