将参数传递给按钮的命令选项 [英] Passing parameters to a button's command option
本文介绍了将参数传递给按钮的命令选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用带有参数的按钮功能?
How do I use a function with parameters for a button?
from Tkinter import *
def function(x, y):
x * y
root = Tk()
button_1 = Button(root, text='Times two numbers', command=function)
那么我该如何通过?我可以吗?
So how do I pass it? Would I:
button_1 = Button(root, text='Times two numbers', command=function(z,v))
如果那行不通,请有人解释一下它的工作原理,我见过有人使用 lambda
,但我不理解.
If that doesn't work can someone please explain how it works I saw people using lambda
but I don't understand it.
推荐答案
是的,您可以为此使用 lambda
:
Yes, you can use a lambda
for this:
button_1 = Button(root, text='Times two numbers', command=lambda: function(z,v))
def callback():
function(z,v)
button_1 = Button(root, text='Times two numbers', command=callback)
除了该函数是内联创建的.
except that the function is created inline.
请注意,您不能执行以下操作:
Note that you cannot do:
button_1 = Button(root, text='Times two numbers', command=function(z,v))
因为 function(z,v)
是有效的函数调用,并且在Python解释上述行时将照此执行.因此,会将 command
分配给 function(z,v)
的返回值.
because function(z,v)
is a valid function call and will be executed as such when Python interprets the above line. So, command
will be assigned to the return value of function(z,v)
.
这篇关于将参数传递给按钮的命令选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文