septerr
septerr

Reputation: 6603

Python Kivy Float Layout

I have very little experience with Python and Kivy. I am helping my little nephew with his quest to build a game using the two. We are stuck at something that seems simple.

Consider following code:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
    ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from random import randint
from kivy.graphics import Color, Ellipse, Rectangle
from kivy.uix.floatlayout import FloatLayout
import math

class Fly(Widget):
    pass

class Stick(Widget):
    pass

class FlyBox(Widget):
    pass

class GameArea(FloatLayout):
    pass

class FlyApp(App):
    def build(self):
        gameArea = GameArea()
        flyBox = FlyBox()
        flyBox.canvas.add(Rectangle(pos_hint={'x': 0, 'y': .3}, size_hint=(1, .3)))
        flyBox.canvas.add(Color(1, 0, 0))
        gameArea.add_widget(flyBox)
        return gameArea


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

it produces following output:

enter image description here

What we were trying to achieve was:

i.e. if the game area were to be divided into 3 equal sized horizontal bands, the FlyBox should be the middle band. And as the size of game area changes (due to resizing of window), the FlyBox's size and position should change relatively.

We are trying to avoid using a .kv file and instead do everything in Python.

Upvotes: 1

Views: 2802

Answers (1)

FJSevilla
FJSevilla

Reputation: 4543

You only need to use size_hint_y property to set the correct height (1/3rd the parent height) and pos_hint property to position it in the center.

Using kivy languaje:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder

kv_text = '''
<GameArea>:
    Widget:
        id: flybox
        size_hint_y: 1/3
        pos_hint: {'x': 0, 'center_y': .5}
        canvas.before:
            Color:
                rgba: 1,1,1,1
            Rectangle:
                pos: self.pos
                size: self.size
'''

class GameArea(FloatLayout):
    pass

class FlyApp(App):
    def build(self):
        Builder.load_string(kv_text)
        return GameArea()

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

Output:

enter image description here

Upvotes: 1

Related Questions