python kivy:如何使开关按钮与轮播一起使用

时间:2019-04-17 04:07:28

标签: python-3.x kivy kivy-language

我得到:

  

AttributeError:“轮播”对象没有属性“ switch_on”

每当我尝试单击按钮时发生错误

------- main.py ----------

class main(App):
    def build(self):



        class SampBoxLayout(BoxLayout):


            # For Switch
            def switch_on(self, instance, value):
                if value is True:
                    print("Switch On")
                else:
                    print("Switch Off")



        return Carousel()



sample_app = kv_main()
sample_app.run()

---------- main.kv --------------

Label:
    text: "Page 1"
    size_hint: 1, .1
    width :100

    SampBoxLayout:


        # ----------Switch ----------
        BoxLayout:

            BoxLayout:
                orientation: "horizontal"
                size_hint_x: .25
                CustLabel:
                    text: "On / Off"

                    Switch:
                        id: switch_id
                        on_active: root.switch_on(self, self.active)# <--need help on this


Label:
    text: "Page 2"
    size_hint: 1, .1
    width :100

    Button:
        text: "Button 2.1"
        size_hint: None, None
        width :100



Label:
    text: "Page 3"
    size_hint: 1, .1
    width :100

    Button:
        text: "Button 3.1"
        size_hint: None, None
        width :100

1 个答案:

答案 0 :(得分:0)

您正在使用root.switch_on。如错误所示,您的根类是轮播。由于SampBoxLayout不是root用户,因此您应该给SampBoxLayout一个id,并用它的id进行调用。
根据您的示例进行了编辑:

SampBoxLayout:
    id: samp
    BoxLayout:

        BoxLayout:
            orientation: "horizontal"
            size_hint_x: .25
            CustLabel:
                text: "On / Off"

                Switch:
                    id: switch_id
                    on_active: samp.switch_on(self, self.active)

我不知道您在发布此消息时是否做错了什么,或者您的代码是否真的像这样。但是您不应该在应用程序类中定义类。将类保持在顶层以在kv中访问它们。
而且您的kv代码不寻常。您的标签中有小部件。