如何在我的所有屏幕上放置一个带有时间的标签

时间:2017-06-24 07:06:14

标签: python kivy

我从kivy开始并有一些问题。我有几个屏幕和按钮的代码。如何在我的所有屏幕上放置一个带有时间或类似内容的标签?在下面的代码中,我创建了一个屏幕,但我不想在各个屏幕上放置3个单独的标签

main.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import StringProperty, ObjectProperty
from kivy.clock import Clock
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import ScreenManager, Screen

Builder.load_string("""
<StartScreen>:
    BoxLayout:
        orientation: 'vertical'
        Button:
            text: 'Start >'
            size_hint_y: None
            hight: '40dp'
            on_press: root.manager.current = 'second'

<SecondScreen>:
    BoxLayout:
        orientation: 'vertical'
        Button:
            text: 'Test2'
            size_hint_y: None
            hight: '40dp'
            on_press: root.manager.current = 'end'

<EndScreen>:
    BoxLayout:
        Button:
            text: 'Test3'
            size_hint_y: None
            hight: '40dp'
            on_press: root.manager.current = 'start'
""")

#declarate both screens
class StartScreen(Screen):
        pass

class SecondScreen(Screen):
        pass

class EndScreen(Screen):
        pass

#create the screen manager
sm = ScreenManager()
sm.add_widget(StartScreen(name='start'))
sm.add_widget(SecondScreen(name='second'))
sm.add_widget(EndScreen(name='end'))

class TutorialApp(App):
    def build(self):
        return sm

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

1 个答案:

答案 0 :(得分:0)

这是一种基于https://stackoverflow.com/a/18926863/6646710

的可能解决方案

下面的代码定义了一个显示时间的标签。

import time

class IncrediblyCrudeClock(Label):
    def __init__(self, **kwargs):
        super(IncrediblyCrudeClock, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, 1)

    def update(self, *args):
        self.text = time.asctime()

update函数从python time模块获取当前时间。该时间用于更新标签的text属性。在init方法中,clock模块用于每秒调度对此更新函数的调用。

接下来,我将此Label添加到kv字符串中的所有kivy屏幕。

<StartScreen>:
    BoxLayout:
        orientation: 'vertical'
        Button:
            text: 'Start >'
            size_hint_y: None
            hight: '40dp'
            on_press: root.manager.current = 'second'
        IncrediblyCrudeClock:

<SecondScreen>:
    BoxLayout:
        orientation: 'vertical'
        Button:
            text: 'Test2'
            size_hint_y: None
            hight: '40dp'
            on_press: root.manager.current = 'end'
        IncrediblyCrudeClock:

<EndScreen>:
    BoxLayout:
        Button:
            text: 'Test3'
            size_hint_y: None
            hight: '40dp'
            on_press: root.manager.current = 'start'
        IncrediblyCrudeClock:

最终结果看起来像enter image description here