gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:22:45 32 4
gpt4 key购买 nike

我想在 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()

最佳答案

根据documentation for halign :

This doesn’t change the position of the text texture of the Label(centered), only the position of the text in this texture. Youprobably want to bind the size of the Label to the texture_size or seta 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)

关于python - Kivy 按钮文本对齐 (halign) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62953188/

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