简体   繁体   中英

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:

在此处输入图片说明

What we were trying to achieve was:

  • The FlyBox's height should be 1/3rd the height of the GameArea's height.
  • The FlyBox's width should be same as GameArea's width.
  • The FlyBox's x coordinate should be 0 and its y coordinate should be 1/3rd the height of GameArea.

ie 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.

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:

在此处输入图片说明

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