python - 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
字符串中,我使用的是 ,而不是root
(这将是) ,它指的是类。StackLayout
app
theApp
推荐阅读
- c - 存储和打印结构数组无法按预期工作
- r - How to get rid of INCOMPLETE STRING error in ShinyApp R?
- java - 在Java中的排序矩阵中搜索
- powershell - 如何为每个 npm 脚本打开多个拆分终端?
- python - Kapitza 振荡器动画太慢且不稳定
- gnuplot - Gnuplot - 设置一个函数
- python - 有没有办法可以配对一个以后可以自行删除的数组的内容?(秘密圣诞老人计划)
- python-3.x - 在不同变量中分配 While 循环的值的问题
- resteasy - RESTEASY002020:quarkus 1.0 Final 和 RestEeasy JAX-RS 资源未处理的异步异常
- sql - 运行 Spark SQL 查询的问题 - 未找到列