kivy python将参数传递给按钮点击的功能 [英] kivy python passing parameters to fuction with button click

查看:1086
本文介绍了kivy python将参数传递给按钮点击的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在按下按钮调用参数时,我无法传递参数。可以用kivy语言这样做:

 按钮:
on_press:root.my_function('btn1')

但是我想用python来做,因为我想创建更多的按钮与一个循环。目前我在python中调用我的函数是这样的:
$ b $ $ p $ Button(on_press = self.my_function)


$ b

但是正如我所说的,如果我尝试传递一个参数给这个函数,我得到一个'AssertionError:None不可调用' ,像这样:

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


解决方案

b

这是将该函数作为参数传递



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

这是调用函数并将返回值作为参数传递给 on_press 。由于返回的值为None,因此会出错。



您需要传递一个新函数来调用您的普通函数并自动传递参数。通常,从functools中使用 functools.partial

 导入部分
Button(on_press = partial(self.my_function,'btn1'))

您也可以使用lambda函数:

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


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')

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)

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)

This is passing the function as an argument.

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

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.

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'))

You can also use a lambda function:

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

这篇关于kivy python将参数传递给按钮点击的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆