【问题标题】:Kivy pass variables to function in classKivy 将变量传递给类中的函数
【发布时间】:2016-01-15 13:12:03
【问题描述】:

我在玩 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)

这些按钮调用身份验证:

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

【问题讨论】:

    标签: python function class kivy


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2017-04-15
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多