我目前正在使用python和kivy开发GUI。我的目标是在屏幕上显示标签/小部件,该标签/小部件显示当前时间并自行更新。稍后,我想使用该值(时间)来填写其他输入小部件(“使用当前时间”)。
这是屏幕的.kv文件,我希望在上面显示时间。 现在,我添加了一个按钮,该按钮将触发main.py中的change_time函数,然后使用标签ID“ current_time”更新文本/标签。最后,这应该自动发生,无需使用按钮
<ClockScreen>:
FloatLayout:
#Background color
canvas:
Color:
rgb: utils.get_color_from_hex("#00a7d8")
Rectangle:
size: self.size
pos: self.pos
#Input-Fields and Labels
GridLayout:
cols: 1
pos_hint: {"top": 1, "right": 1}
size_hint: 1, .8
Label:
id: current_time
text: "Current Time"
Button:
on_press:
root.change_time()
[...]
这是main.py文件,在我的类中为ClockScreen定义了函数change_time。
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.uix.button import ButtonBehavior
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.spinner import Spinner
from kivy.properties import ObjectProperty
import requests
import time
[...]
class ClockScreen(Screen):
def change_time(self):
time = time.asctime()
current_time = self.ids.current_time
current_time.text = time
print(current_time.text)
[...]
GUI = Builder.load_file("main.kv")
class MainApp(App):
def build(self):
return GUI
def change_screen(self, screen_name):
screen_manager = self.root.ids['screen_manager']
screen_manager.transition = NoTransition()
screen_manager.current = screen_name
MainApp().run() #Um die Mainapp zu starten
如果我运行此命令,则会收到错误“ UnboundLocalError:分配前已引用本地变量'time'” 。当我在ClockScreen类之外定义变量时间时,它可以工作,但是时间是静态的,仅更新一次(当我运行该应用程序时)。
如何在不使用按钮调用函数的情况下自动更新当前时间,然后将其显示在ClockScreen上?谢谢!