我想延迟函数调用.(或者在我看来: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等特定时间间隔这不是我要搜索的内容.:-(
问题是您在创建按钮时调用该函数,而不是传递TK在单击按钮时将调用的可调用对象.通常你只需要传递函数:
button1=Button(master=main, text='b1', command=bf)
但由于你想传递参数,bf
你需要将它包装在lambda中:
button1=Button(master=main, text='b1', command=lambda: bf('b1'))