简体   繁体   中英

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. I put this code in the on_enter function of a screen:

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. For example, for fixed height of 50dp, without changing width, it would be:

Button:
    size_hint_y: None
    height: '50dp'

on in 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. To correct this, use ScrollView widget to scroll them up and down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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