Kivy 开关回调
Kivy Switch Callback
我是 Kivy 的新手。请帮助我使开关小部件正常工作。
这是我当前的代码:
from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
StackLayout:
orientation: 'lr-tb'
padding: 10
spacing: 5
Button:
text: 'S1'
size_hint: .2,.1
Button:
text: 'S2'
size_hint: .2,.1
Button:
text: 'S3'
size_hint: .2,.1
Switch:
id: switch_id
on_active: root.switch_on(self, self.active)
size_hint: .2, .1
'''))
我知道我需要添加以下代码,但我不确定如何使用 类 来实现。这是我提到的补充:
def switch_on(self, instance, value):
if value is True:
print("Switch On")
else:
print("Switch Off")
如能提供有关如何正确组合所有内容的任何帮助,我们将不胜感激:)
这是一个如何操作的例子:
from kivy.app import App
from kivy.lang import Builder
theRoot = Builder.load_string('''
StackLayout:
orientation: 'lr-tb'
padding: 10
spacing: 5
Button:
text: 'S1'
size_hint: .2,.1
Button:
text: 'S2'
size_hint: .2,.1
Button:
text: 'S3'
size_hint: .2,.1
Switch:
id: switch_id
on_active: app.switch_on(self, self.active)
size_hint: .2, .1
''')
class theApp(App):
def build(self):
return theRoot
def switch_on(self, instance, value):
if value is True:
print("Switch On")
else:
print("Switch Off")
if __name__ == '__main__':
theApp().run()
请注意,在 kv
字符串中,我使用 app
而不是 root
(即 StackLayout
),它指的是 theApp
class.
我是 Kivy 的新手。请帮助我使开关小部件正常工作。 这是我当前的代码:
from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
StackLayout:
orientation: 'lr-tb'
padding: 10
spacing: 5
Button:
text: 'S1'
size_hint: .2,.1
Button:
text: 'S2'
size_hint: .2,.1
Button:
text: 'S3'
size_hint: .2,.1
Switch:
id: switch_id
on_active: root.switch_on(self, self.active)
size_hint: .2, .1
'''))
我知道我需要添加以下代码,但我不确定如何使用 类 来实现。这是我提到的补充:
def switch_on(self, instance, value):
if value is True:
print("Switch On")
else:
print("Switch Off")
如能提供有关如何正确组合所有内容的任何帮助,我们将不胜感激:)
这是一个如何操作的例子:
from kivy.app import App
from kivy.lang import Builder
theRoot = Builder.load_string('''
StackLayout:
orientation: 'lr-tb'
padding: 10
spacing: 5
Button:
text: 'S1'
size_hint: .2,.1
Button:
text: 'S2'
size_hint: .2,.1
Button:
text: 'S3'
size_hint: .2,.1
Switch:
id: switch_id
on_active: app.switch_on(self, self.active)
size_hint: .2, .1
''')
class theApp(App):
def build(self):
return theRoot
def switch_on(self, instance, value):
if value is True:
print("Switch On")
else:
print("Switch Off")
if __name__ == '__main__':
theApp().run()
请注意,在 kv
字符串中,我使用 app
而不是 root
(即 StackLayout
),它指的是 theApp
class.