我正在尝试在Kivy程序中实现滚动标签,并发现这个有效的示例(稍加修改):
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.lang import Builder
long_text = "".join(["this is a long line "+str(n)+"\n" for n in range(1,101)])
Builder.load_string('''
<ScrollableLabel>:
Label:
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
text: root.text
''')
class ScrollableLabel(ScrollView):
text = StringProperty('')
class ScrollApp(App):
def build(self):
return ScrollableLabel(text=long_text)
if __name__ == "__main__":
ScrollApp().run()
部分用于我自己的教育,我试图将此示例转换为不使用Builder(而不是使用.kv文件)。我已将上述示例修改为:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
long_text = "".join(["this is a long line "+str(n)+"\n" for n in range(1,101)])
class ScrollableLabel(ScrollView):
text = StringProperty('')
def __init__(self, **kwargs):
super(ScrollableLabel, self).__init__(**kwargs)
self.label = Label(size_hint_y=None, text=self.text)
self.label.height = self.label.texture_size[1]
self.label.text_size = (self.label.width, None)
self.add_widget(self.label)
class ScrollApp(App):
def build(self):
return ScrollableLabel(text=long_text)
if __name__ == "__main__":
ScrollApp().run()
对于我明显未经训练的眼睛,这些程序看起来应该是等同的。但是,我的(第二个)版本无法正常工作(在几个方面)。
所以我的问题是双重的:为什么第二个版本与第一个版本的工作方式不同,并且(如果答案从第一个版本开始并不明显),我怎么能这样做呢?
谢谢! -David
答案 0 :(得分:0)
试试这个:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.clock import Clock
long_text = "".join(["this is a long line "+str(n)+"\n" for n in range(1,101)])
class ScrollableLabel(ScrollView):
text = StringProperty('')
def __init__(self, **kwargs):
super(ScrollableLabel, self).__init__(**kwargs)
self.label = Label(size_hint_y=None, text=self.text)
self.add_widget(self.label)
Clock.schedule_once(self.update, 1)
def update(self, *args):
self.label.text_size = (self.label.width, None)
self.label.height = self.label.texture_size[1]
class ScrollApp(App):
def build(self):
return ScrollableLabel(text=long_text)
if __name__ == "__main__":
ScrollApp().run()
现在输出与您的第一个
相同