我是 Kivy 的新手,我制作了一些小应用程序和类似的东西,但现在我在尝试创建左对齐的打字效果文本时遇到了问题。
我的想法是让文本出现在屏幕的一角,类似于终端(我将留下一张取自Pydroid 的示例图像)。我能够用静态文本实现这一点,但对于我的项目,我还需要一个打字效果,我也设法实现了。但是,当试图将两者结合起来时,我无法让文本左对齐。它总是留在中间。
我的代码:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.clock import Clock
class MyLabel(Label):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.text_to_type= self.text
self.text = ""
Clock.schedule_interval(self.type_text, 0.05)
def type_text(self, txt):
if len(self.text) < len(self.text_to_type):
self.text += self.text_to_type[len(self.text)]
class Example(App):
def build(self):
self.root = FloatLayout()
self.root.add_widget(MyLabel(text='''
That's a typing text!
And I'm trying to make it aligned!''',
size_hint=(1.0, 1.0),
halign="left",
valign="bottom"))
return self.root
if __name__ == "__main__":
Example().run()
我怎样才能让它向左对齐,看起来像我发布的示例照片? 提前致谢!
您需要设置
text_size
的 Label
属性,以便对齐工作(参见 documentation)。这是您的代码的修改版本:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.clock import Clock
class MyLabel(Label):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.text_to_type = self.text
self.text = ""
Clock.schedule_interval(self.type_text, 0.05)
def type_text(self, txt):
if len(self.text) < len(self.text_to_type):
self.text += self.text_to_type[len(self.text)]
kv = '''
<MyLabel>:
size_hint: (1.0, 1.0)
text_size: self.size
halign: "left"
valign: "bottom"
'''
class Example(App):
def build(self):
Builder.load_string(kv)
self.root = FloatLayout()
self.root.add_widget(MyLabel(text='''
That's a typing text!
And I'm trying to make it aligned!'''))
return self.root
if __name__ == "__main__":
Example().run()