简体   繁体   English

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

[英]Size_hint and pos_hint of kivy not working when adding buttons programmatically in python

I am querying Mongolab for the number of documents in a collection, then I want to add one button per document found. 我正在查询Mongolab以获取集合中文档的数量,然后我想为找到的每个文档添加一个按钮。 I put this code in the on_enter function of a screen: 我将此代码放在屏幕的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)

However, the layout turns out to be this: 但是,布局实际上是这样的:

在此处输入图片说明

Basically I want the buttons to be more like this: 基本上,我希望按钮更像这样: 在此处输入图片说明

Any suggestions will be much appreciated :) 任何建议将不胜感激:)

If you want to have fixed size buttons in a GridLayout (or a BoxLayout), you have to unset their size_hints. 如果要在GridLayout(或BoxLayout)中具有固定大小的按钮,则必须取消设置其size_hints。 For example, for fixed height of 50dp, without changing width, it would be: 例如,对于50dp的固定高度,不更改宽度,则为:

Button:
    size_hint_y: None
    height: '50dp'

on in py: 在py中:

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

PS: remember, the buttons might overflow the screen, if too many topics are given. PS:请记住,如果给出过多的主题,则按钮可能会溢出屏幕。 To correct this, use ScrollView widget to scroll them up and down. 若要更正此问题,请使用ScrollView小部件上下滚动它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM