kivy python通过按钮单击将参数传递给函数

2022-01-15 00:00:00 python kivy function button

问题描述

按下按钮调用函数时,我无法将参数传递给函数.用 kivy 语言可以这样做:

I am having trouble passing parameters to function when calling it with button press. One could do it like this in kivy language:

Button: 
   on_press: root.my_function('btn1')

但我想用 python 来做,因为我想用循环创建更多的按钮.目前我在 python 中这样调用我的函数:

but I would like to do it in python, as I would like to create a larger number of buttons with a loop. Currently I call my function in python like this:

Button(on_press=self.my_function)

但正如我所说,如果我尝试像这样将参数传递给函数,我会得到一个AssertionError: None is not callable",如下所示:

but as I said, if I try to pass a parameter to the function like this, I get an 'AssertionError: None is not callable', like this:

Button(on_press=self.my_function('btn1'))


解决方案

Button(on_press=self.my_function)

这是传递函数作为参数.

Button(on_press=self.my_function('btn1'))

这是调用函数并将返回值作为参数传递给on_press.由于返回值为 None,因此您会收到错误消息.

This is calling the function and passing the returned value as the argument to on_press. Since the returned value is None, you get your error.

您需要传递一个调用普通函数并自动传递参数的新函数.总的来说,使用 functools.partial 比较方便:

You instead need to pass a new function that calls your normal function and automatically passes the argument. In general, it's convenient to use functools.partial:

from functools import partial
Button(on_press=partial(self.my_function, 'btn1'))

您还可以使用 lambda 函数:

You can also use a lambda function:

Button(on_press=lambda *args: self.my_function('btn1', *args))

相关文章