kivy时钟更新标签问题
Issue with kivy Clock updating label
我正在制作一个应该每秒更新一次的标签。我试着用时钟时间表来做,但它似乎不起作用。奇怪的是,如果我使用按钮调用相同的功能,它会正常工作。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.clock import Clock
class FirstLayout(BoxLayout):
r = 0
def __init__(self, **kwargs):
super(FirstLayout, self).__init__(**kwargs)
self.change = self.ids.temp_label
def my_callback(self, *args):
self.r += 1
print self.r
t = str(self.r)
self.change.text = t
class TryApp(App):
def build(self):
Clock.schedule_interval(FirstLayout().my_callback, 1)
return FirstLayout()
app = TryApp()
app.run()
.kv 文件:
<FirstLayout>:
orientation: 'vertical'
Label:
id: temp_label
text: 'something'
Button:
on_press: root.my_callback()
当我 运行 代码时,我得到的打印件显示函数是 运行ning 但标签没有更新。我的逻辑有什么问题吗?
提前致谢。
PS:我知道这里有几个关于这个的问题,遗憾的是,我发现的那些问题得到了关于使用时钟的回答,我已经这样做了
问题是回调是针对您不使用的实例:
def build(self):
Clock.schedule_interval(FirstLayout().my_callback, 1) #<--- FirstLayout created and never used
return FirstLayout() #this one will be used :(
相反,您需要调用您正在使用
的 FirstLayout 的方法
def build(self):
first_layout = FirstLayout() # "There should be one ..." :)
Clock.schedule_interval(first_layout.my_callback, 1)
return first_layout
我正在制作一个应该每秒更新一次的标签。我试着用时钟时间表来做,但它似乎不起作用。奇怪的是,如果我使用按钮调用相同的功能,它会正常工作。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.clock import Clock
class FirstLayout(BoxLayout):
r = 0
def __init__(self, **kwargs):
super(FirstLayout, self).__init__(**kwargs)
self.change = self.ids.temp_label
def my_callback(self, *args):
self.r += 1
print self.r
t = str(self.r)
self.change.text = t
class TryApp(App):
def build(self):
Clock.schedule_interval(FirstLayout().my_callback, 1)
return FirstLayout()
app = TryApp()
app.run()
.kv 文件:
<FirstLayout>:
orientation: 'vertical'
Label:
id: temp_label
text: 'something'
Button:
on_press: root.my_callback()
当我 运行 代码时,我得到的打印件显示函数是 运行ning 但标签没有更新。我的逻辑有什么问题吗?
提前致谢。
PS:我知道这里有几个关于这个的问题,遗憾的是,我发现的那些问题得到了关于使用时钟的回答,我已经这样做了
问题是回调是针对您不使用的实例:
def build(self):
Clock.schedule_interval(FirstLayout().my_callback, 1) #<--- FirstLayout created and never used
return FirstLayout() #this one will be used :(
相反,您需要调用您正在使用
的 FirstLayout 的方法def build(self):
first_layout = FirstLayout() # "There should be one ..." :)
Clock.schedule_interval(first_layout.my_callback, 1)
return first_layout