Rick Freeman
Rick Freeman

Reputation: 15

Kivy Button text disappears when using size_hint

newbie programmer here. Trying to instantiate a button in my python/kivy application, and whenever I set a size_hint, the button text disappears. The goal is to have a button that is 0.1 x 0.1 of the window, and have it display text.

Here is my python file (minimum reproducible error):

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.window import Window


class GameScreen(Widget):
    pass


class test801App(App):
    def build(self):
        return GameScreen()


if __name__ == '__main__':
    test801App().run()

and here is my .kv file:

#:kivy 2.3.0

<GameScreen>:
    canvas:
        Color:
            rgba: 0, 0, 1, 1  # Blue (For the border)
        Rectangle:
            pos: root.x, root.y
            size: root.width, root.height
        Color:
            rgba: 1, 1, 1, 1  # White
        Rectangle:
            pos: root.x + 5, root.y + 5
            size: root.width - 10, root.height - 10

    FloatLayout:
        pos: 0,0
        size: root.width, root.height

        Button:
            pos_hint: {'x': .05, 'y': .05 }
            #size_hint: root.width * 0.1, root.height * .1
            font_size: 22
            bold: True
            background_normal: ''
            background_color: 0.2, 0.7, .2, 1 # Green
            color: 1, 0, 0, 1  # Red
            text_box_size: self.width, self.height
            text: 'Hello'

With "size_hint" commented out, I get the text. When I uncomment that line, the text disappears.

It works when the Button is part of a GridLayout (which was part of a FloatLayout at same level as canvas. It stopped working when I instantiated the Button as part of the FloatLayout directly.

I tried adding a text_box_size constraint to make sure it wasn't displaying the text outside the window. I tried changing the text color. I tried changing the background color. I tried adding/deleting background_normal.

As a side note, the size_hint doesn't make the button 0.1x0.1 either. That also worked when the Button was part of the GridLayout. I haven't tried to debug that problem yet, may be related???

Upvotes: 0

Views: 43

Answers (1)

John Anderson
John Anderson

Reputation: 39012

The size_hint is not a pixel value, it is a fraction of the containers size. Try replacing:

size_hint: root.width * 0.1, root.height * .1

with:

size_hint: 0.1, 0.1

See the documentation.

Upvotes: 2

Related Questions