jasonC
jasonC

Reputation: 347

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:

enter image description here

Basically I want the buttons to be more like this: enter image description here

Any suggestions will be much appreciated :)

Upvotes: 0

Views: 1919

Answers (1)

jligeza
jligeza

Reputation: 4693

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.

Upvotes: 1

Related Questions