事件绑定中的函数回调,带和不带括号

编程入门 行业动态 更新时间:2024-10-23 07:24:03
本文介绍了事件绑定中的函数回调,带和不带括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我刚开始使用我的第一个 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 08:25:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   不带   绑定   回调   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!