【问题标题】:(Python Kivy) Indexing Which Button Was Pressed(Python Kivy)索引哪个按钮被按下
【发布时间】:2017-07-10 01:35:56
【问题描述】:
我正在尝试找出一种方法来索引在 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 结束
【问题讨论】:
标签:
python
function
parameter-passing
kivy
kivy-language
【解决方案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>