【发布时间】:2021-06-04 08:23:53
【问题描述】:
我想使用 Kivy 时钟每秒更新标签中的文本。
当按下“TimeDisplay”中的按钮时,我希望时钟调用“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的标签文本?
【问题讨论】: