我问了一个关于更新标签文字的问题(Kivy change label text with python) - 它得到了解答并且正在运行但我已经尝试了几个小时试图将我正在运行的代码调整到ScreenManager
所以我可以有多个屏幕。我已经把代码减少到了我无法工作的基本内容。
ScreenManager
代码打破了解决方案,我知道问题是什么,我无法解决它。代码在shell中工作,文本和时间更新但不是标签,我无法将return self.first_screen
添加到Kivy def build
,因此它不绑定到the_time: _id_lbl_time
- 任何帮助/指针真的很感激。
from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import ListProperty, StringProperty, ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen, WipeTransition, FadeTransition
from kivy.uix.anchorlayout import AnchorLayout
from kivy.clock import Clock
import time
from datetime import datetime, timedelta
class FirstScreen(Screen):
def update_time(self, sec):
MyTime = time.strftime("%H:%M:%S")
print MyTime # to test update_time is called etc
self.the_time.text = MyTime #<---- self.the_time isn't working
class SecondScreen(Screen):
def update_text(self, sec):
MyText = 'New Text'
print MyText # to test update_text is called etc
self.the_set.text = MyText #<---- self.the_set isn't working
class MyScreenManager(ScreenManager):
pass
Builder.load_string('''
<FirstScreen>:
name: 'first'
the_time: _id_lbl_time
BoxLayout:
orientation: 'vertical'
Label
id: _id_lbl_time
text: 'Clock'
font_size: 30
BoxLayout:
Button:
text: 'New Here'
font_size: 20
size: 200, 50
size_hint: None, None
on_release: app.root.current = 'second'
<SecondScreen>:
name: 'second'
the_set: _id_lbl_set
BoxLayout:
orientation: 'vertical'
Label:
id: _id_lbl_set
text: 'New Here'
font_size: 30
BoxLayout:
Button:
text: 'Main'
font_size: 20
size: 200, 50
size_hint: None, None
on_release: app.root.current = 'first'
''')
class ScreenManagerApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(FirstScreen(name='first'))
sm.add_widget(SecondScreen(name='second'))
self.first_screen = FirstScreen()
self.sec_screen = SecondScreen()
return sm #<---- I can't return self.first_screen etc here?
def on_start(self):
Clock.schedule_interval(self.first_screen.update_time, 1) # 1 second
Clock.schedule_interval(self.sec_screen.update_text, 2)
ScreenManagerApp().run()
答案 0 :(得分:0)
我不能在这里返回self.first_screen等?
没有。 ScreenManager
窗口小部件之上必须有Screen
,否则它只是RelativeLayout
,因为它在源代码中的定义。
初学者经历了一个非常常见的错误。您为FirstScreen()
使用了一个SecondScreen()
和ScreenManager
实例(这些是可见的),然后您创建了另一个实例:
self.first_screen = FirstScreen()
self.sec_screen = SecondScreen()
然后用于Clock
:
Clock.schedule_interval(self.first_screen.update_time, 1)
Clock.schedule_interval(self.sec_screen.update_text, 2)
这意味着实际未添加到的实例中的text
属性作为小部件用于更新。实例存在,因此除了可视化之外没有触发错误→您没有看到值,因为您使用了错误的实例。
更正build()
:
def build(self):
sm = ScreenManager()
self.first_screen = FirstScreen(name='first')
self.sec_screen = SecondScreen(name='second')
sm.add_widget(self.first_screen)
sm.add_widget(self.sec_screen)
return sm