問題描述
按下按鈕調(diào)用函數(shù)時,我無法將參數(shù)傳遞給函數(shù).用 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 來做,因為我想用循環(huán)創(chuàng)建更多的按鈕.目前我在 python 中這樣調(diào)用我的函數(shù):
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)
但正如我所說,如果我嘗試像這樣將參數(shù)傳遞給函數(shù),我會得到一個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)
這是傳遞函數(shù)作為參數(shù).
Button(on_press=self.my_function('btn1'))
這是調(diào)用函數(shù)并將返回值作為參數(shù)傳遞給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.
您需要傳遞一個調(diào)用普通函數(shù)并自動傳遞參數(shù)的新函數(shù).總的來說,使用 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 函數(shù):
You can also use a lambda function:
Button(on_press=lambda *args: self.my_function('btn1', *args))
這篇關于kivy python通過按鈕單擊將參數(shù)傳遞給函數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!