将参数传递给按钮的命令选项

时间:2014-11-12 17:12:59

标签: python function tkinter

如何使用带按钮参数的功能?

from Tkinter import *
def function(x, y):
    x * y

root = Tk()
button_1 = Button(root, text='Times two numbers', command=function)

那我怎么通过呢?我会:

button_1 = Button(root, text='Times two numbers', command=function(z,v))

如果那不起作用,有人可以解释它是如何工作的我看到人们使用lambda但我不理解它。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用lambda

button_1 = Button(root, text='Times two numbers', command=lambda: function(z,v))

lambda创建了所谓的anonymous function。它等同于:

def callback():
    function(z,v)
button_1 = Button(root, text='Times two numbers', command=callback)

除了函数是内联创建的。


请注意,您无法执行以下操作:

button_1 = Button(root, text='Times two numbers', command=function(z,v))

因为function(z,v)是一个有效的函数调用,并且当Python解释上面的行时将会这样执行。因此,command将被分配给function(z,v)的返回值。