简体   繁体   中英

Pos_hint ans size_hint do not seem to work in my kv file and I do not know why

So, I've been trying some Kivy, and I've introduced just a button in my kv file associated with the following python code:

#importing library
import kivy
kivy.require('1.11.1') #version

#importing functionality
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty

class FloatLayout(Widget):
    username = ObjectProperty(None)
    password = ObjectProperty(None)
    """idle code here, does nothing"""

class howyoudoin(App):
    def build(self):
        return FloatLayout()

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

And here is my kv file:

<Button>:
    font_size:27
    size_hint: 1.0, 1.0
    background_color: 0.1, 0.5, 0.6, 1

<FloatLayout>:
    Button:
        pos_hint:{"top":1.0}
        id: btn
        text: "button"

Somehow, the size_hint ans pos_hint commands just won't work for me. This returns my button, but ignoring the pos_hint and size_hint commands.

The button does not represent the desired position and size

All other attributes do work: when I change font_size in the code, the font_size changes in the run as well. I can't figure out why :(

You are redefining an existing class ( FloatLayout ), and by doing so you are making it a simple Widget as opposed to a Layout . Since your FloayLayout is not a Layout , it does not respect size_hint and pos_hint . Redefining an existing class is generally a bad idea. If you want to extend FloatLayout , try something like this:

#importing library
import kivy

kivy.require('1.11.1') #version

#importing functionality
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty


class MyFloatLayout(FloatLayout):
    username = ObjectProperty(None)
    password = ObjectProperty(None)
    """idle code here, does nothing"""


class howyoudoin(App):
    def build(self):
        return MyFloatLayout()

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

kv file:

<Button>:
    font_size:27
    size_hint: 1.0, 1.0
    background_color: 0.1, 0.5, 0.6, 1

<MyFloatLayout>:
    Button:
        pos_hint:{"top":1.0}
        id: btn
        text: "button"

In the above code MyFloatLayout extends FloatLayout , so the size_hint and pos_hint of the Button will now be honored.

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