当前位置:  开发笔记 > 编程语言 > 正文

python延迟函数调用

如何解决《python延迟函数调用》经验,为你挑选了1个好方法。

我想延迟函数调用.(或者在我看来:python以错误的顺序执行函数).在下面的例子中,我可以编写两个函数bf1和bf2来代替bf(arg),并且它可以按预期工作:只要按下按钮就会调用该函数.但是如果我在函数中包含参数,则函数调用只执行一次.返回函数本身不会改变行为.

你能不能看看它,并给我一个暗示我对python的逻辑或理解是错误的.

from tkinter import *
def bf(str):
    print(str)
    # return print(str)  #alternative(same behaviour)

main=Tk(screenName='screen',baseName='base')
button1=Button(master=main,text='b1',command=bf("b1"))
button2=Button(master=main,text='b2',command=bf("b2")) # runs once (and runs here)
button1.pack()
button2.pack()
mainloop()
print('end')

--google和stackoverflow搜索只返回延迟函数调用1等特定时间间隔这不是我要搜索的内容.:-(



1> Daniel Rosem..:

问题是您在创建按钮时调用该函数,而不是传递TK在单击按钮时将调用的调用对象.通常你只需要传递函数:

button1=Button(master=main, text='b1', command=bf)

但由于你想传​​递参数,bf你需要将它包装在lambda中:

button1=Button(master=main, text='b1', command=lambda: bf('b1'))

推荐阅读
小色米虫_524
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有