Python ttk.Button -命令,无需按下按钮即可运行
我正在用 ttk 在 python 中制作一个小脚本,但遇到一个问题,函数在不应该运行的地方运行。按钮代码如下:
btReload = ttk.Button(treeBottomUI, text="Reload", width=17, command=loadModelTree(treeModel)) btReload.pack(side="left")
函数如下:
def loadModelTree(tree): print ("Loading models...") allModels = os.listdir(confModPath) for chunk in allModels: ...
由于某种原因,函数在没有按下按钮的情况下运行。为什么?
I'm making a small script in python with ttk and I have a problem where a function runs where it shouldn't. The button code looks as follows:
btReload = ttk.Button(treeBottomUI, text="Reload", width=17, command=loadModelTree(treeModel)) btReload.pack(side="left")
and the function is as this:
def loadModelTree(tree): print ("Loading models...") allModels = os.listdir(confModPath) for chunk in allModels: ...
For some reason, the function runs without the button being pressed. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
马库斯,是的,这是正确的解决方案,但这并不是因为您不能在小部件标注中使用多参数命令。考虑一下,在您的原始代码中,
...command=loadModelTree(treeModel)...
是该方法的调用。 Lambda 允许您抽象命令,这样您就可以拥有任意数量的参数,而不会通过调用它来混淆解释器,例如...command=lambda arg1=myarg1, arg2=myarg2, arg3=myarg3: myCallout(arg1 、arg2、arg3)...
。我希望这能让正在发生的事情变得更清楚一些。
Markus, yes, that's the right solution, but it is not because you can't use multi-argument commands in widget callouts. Consider, in your original code,
...command=loadModelTree(treeModel)...
is an invocation of the method. Lambda allows you to abstract the command so you can have an arbitrary number of arguments without confusing the interpreter by invoking it, e.g.,...command=lambda arg1=myarg1, arg2=myarg2, arg3=myarg3: myCallout(arg1, arg2, arg3)...
.I hope that makes what is going on a bit clearer.
好吧,当我找到答案时,我会回答我自己的问题。
看来 ttk.button 命令不支持向函数发送参数,因此解决方法如下:
简单!
Well, as I found the answer, I'll answer my own question.
It appers that ttk.button commands does not support sending arguments to functions so the work around is to do as follows:
Simple as pie!