我正在尝试制作一个简单的聊天流媒体。我正在努力解决的是让聊天消息左对齐并根据窗口大小动态换行文本。
这个想法是将聊天消息显示为网格布局中的标签。
class ChatMessage(Label):
def __init__(self, *args, **kwargs):
super(ChatMessage, self).__init__(*args, **kwargs)
self.text_size = self.size
self.halign = 'left'
class Root(ScreenManager):
def __init__(self, *args, **kwargs):
super(ScreenManager, self).__init__(*args, **kwargs)
self.ids.chatstream.bind(minimum_height=self.ids.chatstream.setter('height'))
self.add_message()
def add_message(self):
for x in xrange(50):
label = ChatMessage(text='Im still not completely sure I understand the mechanisms at work here, though.. Im still not completely sure I understand the mechanisms at work here, though.. Im still not completely sure I understand the mechanisms at work here, though.' + str(x))
self.ids.chatstream.add_widget(label)
self.ids.scroller.scroll_y = 0
kv 文件:
<Root>:
Screen:
name: 'main'
BoxLayout:
orientation: 'vertical'
Button:
text: ''
on_release: app.root.current = 'chat'
Screen:
name: 'chat'
BoxLayout:
orientation: 'vertical'
ScrollView:
id: scroller
do_scroll_x: False
GridLayout:
id: chatstream
cols: 1
padding: (10, 15)
spacing: 20
size_hint_y: None
Button:
text: ''
on_release: app.root.current = 'main'
设置 ChatMessage 实例的大小,例如
<ChatMessage>
size_hint_y: None
height: self.texture_size[1] # the size needed to fit the text
text_size: self.width, None
同时删除python size中的text_size设置。如果您也在 kv 中设置了 halign,则可以完全删除 __init__
。
我是一名优秀的程序员,十分优秀!