Python(Kivy) - 在python

时间:2017-11-24 07:05:23

标签: python-2.7 kivy kivy-language

我的.kv文件中有一个复选框,我想在未选中此复选框时禁用与之关联的文本输入。

我的.py代码

if self.ids.checkbox.active==False:
    self.ids.input.disabled==True
else:
    self.ids.input.disabled==False

我的.kv代码

TextInput:
        id: input
        text: "2fbd3320a168d5c2e35"
        pos_hint: {"x":0.1, "y":0.4}
        size_hint: 0.5,0.05
        background_disabled_normal: ""

    CheckBox:
        id: checkbox
        pos_hint: {"x":0.6, "y":0.4}
        size_hint: 0.05,0.05

我不知道该怎么做,.py代码必须在一个函数中,但是复选框不包含on_release属性。

1 个答案:

答案 0 :(得分:2)

您需要将事件(checkbox.active)与相应的回调相关联。您可以使用bind

在.py文件中执行此操作
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout

kv_text = """\
<MyWidget>
    TextInput:
        id: input
        text: "2fbd3320a168d5c2e35"
        pos_hint: {"x":0.1, "y":0.4}
        size_hint: 0.5,0.05
        background_disabled_normal: ""
        disabled: True

    CheckBox:
        id: checkbox
        pos_hint: {"x":0.6, "y":0.4}
        size_hint: 0.05,0.05
"""

class MyWidget(FloatLayout):
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.ids.checkbox.bind(active=self.disable_input)

    def disable_input(self, checkbox, checked):
        self.ids.input.disabled = not checked


class MyWidgetApp(App):
    def build(self):
        return MyWidget()

def main():
    Builder.load_string(kv_text)
    app = MyWidgetApp()
    app.run()

if __name__ == '__main__':
    main()

另一个选择是在.kv文件中执行:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout

kv_text = """\
<MyWidget>
    TextInput:
        id: input
        text: "2fbd3320a168d5c2e35"
        pos_hint: {"x":0.1, "y":0.4}
        size_hint: 0.5,0.05
        background_disabled_normal: ""
        disabled: not checkbox.active      # <<<<<<<<<

    CheckBox:
        id: checkbox
        pos_hint: {"x":0.6, "y":0.4}
        size_hint: 0.05,0.05
"""

class MyWidget(FloatLayout):
    pass


class MyWidgetApp(App):
    def build(self):
        return MyWidget()

def main():
    Builder.load_string(kv_text)
    app = MyWidgetApp()
    app.run()

if __name__ == '__main__':
    main()

enter image description here