如何在kivy中初始化CheckBox状态

时间:2015-11-08 11:26:04

标签: python kivy

我想从python代码

初始化kivy中CheckBox的值

我试过(参见示例),但它不起作用。有人可以帮忙吗?

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.properties import StringProperty

class MainScreen(BoxLayout):
  BlueText = StringProperty()
  Blue = BooleanProperty()
  Red = BooleanProperty()
  UseColours = BooleanProperty()

  def __init__(self, **kwargs):
    super(MainScreen, self).__init__(**kwargs)
    self.BlueText='Blue'
    self.UseColours=True
    self.Blue=False
    self.Red=True

  def doBlue(self,*args):
    pass

  def doRed(self,*args):
    pass

  def doUseColours(self,*args):
    pass

class BasicApp(App):
    def build(self):
      return MainScreen()

if __name__ == '__main__':
   BasicApp().run()

我的kv文件尝试通过设置'value'来检查是否检查了这些框。这是对的吗?

MainScreen:

<MainScreen>:
    orientation: "vertical"
    GridLayout:
        cols: 2
        Label:
            text: root.BlueText
        CheckBox:
            group: 'colours'
            value: root.Blue
            on_active: root.doBlue(*args)
        Label:
            text: "Red"
        CheckBox:
            group: 'colours'
            value: root.Red
            on_active: root.doRed(*args)
        Label:
            text: "Use colours"
        CheckBox:
            value: root.UseColours
            on_active: root.doUseColours(*args)

1 个答案:

答案 0 :(得分:0)

使用active属性:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    CheckBox:
        active: False
    CheckBox:
        active: True
''')

class MyWidget(BoxLayout):
    pass

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

if __name__ == '__main__':
    MyApp().run()

来自Python代码:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    CheckBox:
        active: root.is_active
    CheckBox:
        active: not root.is_active
    Button:
        text: 'toggle'
        on_press: root.toggle()
''')

class MyWidget(BoxLayout):
    is_active = BooleanProperty(False)

    def toggle(self):
        self.is_active = not self.is_active

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

if __name__ == '__main__':
    MyApp().run()