Kivy按钮文本对齐(halign)不起作用

2024-09-29 01:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将按钮的文本与Kivy中的halign='left'对齐,但它不起作用,并将其居中

这是我的代码:

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty

class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.cols = 1

        for i in range (0,10):
            self.btn = Button(text=str(i),halign='left',background_color =(.3, .6, .7, 1))
            self.btn.bind(on_press=self.pressed)
            self.add_widget(self.btn)


    def pressed(self, instance):
        print ("Name:",instance.text)



class MyApp(App):
    def build(self):
        return MyGrid()


if __name__ == "__main__":
    MyApp().run()

Tags: fromimportselfappdefbuttonpropertieswidget
1条回答
网友
1楼 · 发布于 2024-09-29 01:31:37

根据documentation for ^{}报告:

This doesn’t change the position of the text texture of the Label (centered), only the position of the text in this texture. You probably want to bind the size of the Label to the texture_size or set a text_size.

因此,为了得到想要的结果,您可以定义对Button的扩展,该扩展符合上述文档的建议:

class MyButt(Button):
    pass

Builder.load_string('''
<MyButt>:
    halign: 'left'
    text_size: self.size
    background_color: (.3, .6, .7, 1)
''')

然后在App中使用该类:

class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.cols = 1

        for i in range (0,10):
            self.btn = MyButt(text=str(i))
            self.btn.bind(on_press=self.pressed)
            self.add_widget(self.btn)

相关问题 更多 >