gpt4 book ai didi

python - 如何对齐 ListView 标签?

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:42 25 4
gpt4 key购买 nike

我正在学习如何使用 Kivy,我想知道如何对齐我构建的 ListView 内的标签。

标签默认居中,我想将所有标签向左对齐。

我的代码:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.listview import SimpleListAdapter
from kivy.uix.listview import ListView
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput

class TestApp(App):
def build(self):
messages = ["a", "b"]
layout = BoxLayout(orientation='vertical')

btn1 = Button(text='Hello')
textinput = TextInput(text='Hello world', size_hint=(1, 0.1))
messages.append("sd")
simple_list_adapter = SimpleListAdapter(
data=messages,
cls=Label)
simple_list_adapter.cls

list_view = ListView(adapter=simple_list_adapter)
layout.add_widget(list_view)
layout.add_widget(textinput)
return layout

TestApp().run()

最佳答案

一个简单的解决方案是创建具有所需对齐方式的标签

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.listview import SimpleListAdapter
from kivy.uix.listview import ListView
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput


class LeftLabel(Label):
def __init__(self, **kwargs):
super(LeftLabel, self).__init__(**kwargs)
# https://kivy.org/doc/stable/api-kivy.uix.label.html#text-alignment-and-wrapping
self.halign = "left"
self.bind(size=self.setter("text_size"))


class TestApp(App):
def build(self):
messages = ["a", "b"]
layout = BoxLayout(orientation="vertical")
btn1 = Button(text="Hello")
textinput = TextInput(text="Hello world", size_hint=(1, 0.1))
messages.append("sd")
simple_list_adapter = SimpleListAdapter(data=messages, cls=LeftLabel)
list_view = ListView(adapter=simple_list_adapter)
layout.add_widget(list_view)
layout.add_widget(textinput)
return layout


TestApp().run()

由于您是从 kivy 开始,建议您学习 RecycleView 而不是 ListView,因为后者是 deprecated :

Deprecated since version 1.10.0: ListView has been deprecated, use RecycleView instead.

关于python - 如何对齐 ListView 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com