在python中以编程方式添加按钮时,kivy的size_hint和pos_hint无法正常工作

时间:2016-02-16 10:25:39

标签: python kivy

我正在查询Mongolab中集合中的文档数量,然后我想为每个找到的文档添加一个按钮。我将此代码放在屏幕的on_enter函数中:

def on_enter(self):
    topicconcepts = db.topicconcepts
    topics = topicconcepts.distinct("topic")

    for idx, topic in enumerate(topics):
        button = Button(text=topic, id=str(idx), buttonPos = idx, size=(self.width,20), pos_hint = {'top': 1}, color= (1,1,1,1), halign='center', seq = 'pre')
        # topicBox points to a BoxLayout
        self.topicBox.add_widget(button)

然而,布局结果是这样的:

enter image description here

基本上我希望按钮更像这样: enter image description here

任何建议都将不胜感激:)

1 个答案:

答案 0 :(得分:0)

如果你想在GridLayout(或BoxLayout)中使用固定大小的按钮,你必须取消设置它们的size_hints。例如,对于50dp的固定高度,不改变宽度,它将是:

Button:
    size_hint_y: None
    height: '50dp'
在py:

from kivy.metrics import dp
Button(size_hint_y=None, height=dp(50))

PS:请记住,如果给出的主题太多,按钮可能会溢出屏幕。要更正此问题,请使用ScrollView窗口小部件向上和向下滚动。