我正在尝试进行一个能够同时显示文本和图像的聊天小部件。我希望能够动态添加数据,因为随着时间的流逝数据不断涌入。我决定使用滚动视图并使用网格布局,并超时添加标签和图像实例。问题是,没有渲染图像。我认为这可能是由于它们的大小所致,但是我不确定是否是这种情况,以及如何修复。
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.uix.image import Image
Builder.load_string('''
<SV>:
do_scroll_x: False
GridLayout:
id: layout
cols: 1
spacing: 10
size_hint_y: None
''')
class SV(ScrollView):
def __init__(self, **kwargs):
super(SV, self).__init__(**kwargs)
for i in range(30):
if i % 3 == 0: self.add_iamge('1.jpg')
else: self.add_label(str(i))
def add_label(self, text):
self.ids.layout.add_widget(Label(text=text))
def add_iamge(self, src):
self.ids.layout.add_widget(Image(source=src))
class TestApp(App):
def build(self):
return SV()
if __name__ == '__main__':
TestApp().run()
答案 0 :(得分:1)
我如何确定标签所需的最小高度 渲染正确吗?
使用以下任一选项:
# Label’s size will be set to the text content (plus padding):
<Label>:
size: self.texture_size
或
# Label that can grow vertically but wraps the text at a certain width
<Label>:
text_size: root.width, None
size: self.texture_size
def add_label(self, text):
self.ids.layout.add_widget(Label(text=text))
以下增强功能是必需的。
设置ScrollView
的大小,例如size_hint: 1, None
和size: (Window.width, Window.height)
确保height
可以滚动,例如height: self.minimum_height
size
,例如size_hint_y=None, height=40
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.uix.image import Image
Builder.load_string('''
#:import Window kivy.core.window.Window
<SV>:
do_scroll_x: False
size_hint: 1, None
size: (Window.width, Window.height)
GridLayout:
id: layout
cols: 1
spacing: 10
size_hint_y: None
height: self.minimum_height
''')
class SV(ScrollView):
def __init__(self, **kwargs):
super(SV, self).__init__(**kwargs)
for i in range(30):
if i % 3 == 0:
self.add_iamge('raspberrypi.png')
else:
self.add_label(str(i))
def add_label(self, text):
self.ids.layout.add_widget(Label(text=text, size_hint_y=None, height=40))
def add_iamge(self, src):
self.ids.layout.add_widget(Image(source=src, size_hint_y=None, height=40))
class TestApp(App):
def build(self):
return SV()
if __name__ == '__main__':
TestApp().run()