Python Kivy:self.ids 没有更新标签文本

Python Kivy: self.ids not updating label text

我想使用 Kivy 时钟每秒更新标签中的文本。

当按下 'TimeDisplay' 中的按钮时,我希望时钟调用 class 'Display' 并更新 'Display' 中标签中的文本调用时间。

这是我的 Python 代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
import time
from kivy.properties import StringProperty
import threading
from kivy.clock import Clock
from kivy.uix.label import Label

Window.size = (600, 400)

class WindowManager(ScreenManager):  # class used for transitions between windows
   pass

class TimeDisplay(Screen):
   def on_press(self):
       display = Display()
       Clock.schedule_interval(display.display_time, 1)

class Display(Screen):
   def display_time(self, *args):
       print(self.ids)
       self.current_time = StringProperty()
       self.current_time = time.strftime("%H:%M:%S") #provides local time as a structure format of minutes followed by seconds
       self.ids.time.text = str(self.current_time)


class MyApp(App):
   def build(self):
       layout = Builder.load_file("layout.kv")  # loads the kv file
       return layout


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

这是 kivy 代码:


WindowManager:
#sets up the different screens for the app and the default order that they run in
    transition: NoTransition() #sets all transitions as 'NoTransition'
    TimeDisplay:
    Display:
    #AlarmDisplay:


<Button>:
    background_normal: "" #sets all buttons default background colour to white


<TimeDisplay>
    Button:
        opacity: 0
        on_press:
            root.on_press()
            root.manager.current = "display"

<Display>
    name: "display"

    FloatLayout:

        Label:
            id: time
            color: (1,0.5,0.5,1)
            size_hint: (0.5, 0.5)
            pos_hint: {"center_x": 0.5, "center_y": 0.5}
            opacity: 1
            text: ""
            font_size: 35
            color: ((83/255),(83/255),(83/255),1) #sets the colour of the text (rgba)

为什么 self.ids.time.text 不更新 ID 为 time 的标签的文本?

您的 on_press() 方法中的代码行:

   display = Display()

创建 Display class 的新实例。这个新实例不是出现在您的 GUI 中的实例,因此您对其所做的任何更改都不会出现在您的 GUI 中。您必须引用 GUI 中实际存在的 Display 实例。您可以通过将上面的行替换为:

display = App.get_running_app().root.get_screen('display')