我试图找出一种方法来索引在GridLayout中按下哪个按钮,以便例如,当按下按钮时,我可以将特定图像放在该按钮的背景中。以下是我目前正在做的事情,在添加更多功能之前,使用函数尝试将索引号打印为测试:
for x in range(15):
self.buttons.append(Button())
self.ids.grid_1.add_widget(self.buttons[x])
self.buttons[x].background_normal = 'YOUTUBE.png'
self.buttons[x].background_down = 'opacity.png'
# Make the button switch screens to input from calling the function above
if edit_mode is True:
self.buttons[x].bind(on_release=self.SwitchScreenInput)
self.buttons[x].bind(on_release=self.HoldButtonNum(x))
def HoldButtonNum(x):
print(x)
我得到错误:
TypeError:HoldButtonNum()占用1个位置参数但是2个 给定
使用退出代码1完成处理
答案 0 :(得分:1)
我会做一些观察:
HoldButtonNum
是实例方法,则其第一个参数必须为self
。functools.partial
或lambda
函数将参数传递给事件处理程序。一个例子:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from functools import partial
class MyGridLayout(GridLayout):
cols = 5
def __init__(self):
super(MyGridLayout, self).__init__()
self.buttons = []
for x in range(15):
self.buttons.append(Button())
self.add_widget(self.buttons[x])
self.buttons[x].bind(on_release=partial(self.HoldButtonNum, x))
def HoldButtonNum(self, x, instance):
print('Button instance:', instance)
print('Button index in list:', x)
class MyKivyApp(App):
def build(self):
return MyGridLayout()
def main():
app = MyKivyApp()
app.run()
if __name__ == '__main__':
main()
按下按钮时,输出如下:
Button index in list: 1 Button instance: <kivy.uix.button.Button object at 0x0000018C511FC798>