Kivy将变量传递给类中的函数

时间:2015-10-16 17:31:40

标签: python function class kivy

我和Kivy一起玩,并建立了一些按钮:

    for i in range(30):
        self.user = str(i)
        self.btn = Button(text=self.user, size_hint_y=None, height=40)
        self.btn.bind(on_press=self.auth(self.user))
        self.layout.add_widget(self.btn)

这些按钮调用auth:

def auth(mytext,instance):
    print "auth called"
    popup = Popup(title="success",
        content=Label(text=mytext),
        size=(100, 100),
        size_hint=(0.3, 0.3),
        auto_dismiss=False)
    popup.open()

为什么我没有将包含字符串的self.user传递给auth函数mytext变量?

我得到AssertionError: None is not callable

1 个答案:

答案 0 :(得分:0)

包含所按按钮的所有内容的实例。

for i in range(30):
    self.user = str(i)
    self.btn = Button(text=self.user, size_hint_y=None, height=40)
    self.btn.bind(on_press=self.auth)
    self.layout.add_widget(self.btn)

def auth(self, instance):
    print "auth called"
    popup = Popup(title="success",
        content=Label(content=Label(text='The button <%s> is being pressed' % instance.text),
        size=(100, 100),
        size_hint=(0.3, 0.3),
        auto_dismiss=False)
    popup.open()

它也可以给按钮一个像

的ID
self.btn = Button(text="Test User", size_hint_y=None, height=40, id=self.user)

并使用instance.id

获取ID
content=Label(content=Label(text='The button <%s> is being pressed' % instance.id)