kivy python passing parameters to fuction with button click(kivy python通过按钮单击将参数传递给函数)
问题描述
按下按钮调用函数时,我无法将参数传递给函数.用 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))
这篇关于kivy python通过按钮单击将参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:kivy python通过按钮单击将参数传递给函数


基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01