Pergunta

I want to show in a button and a label in a widget at left,center position and right,bottom without using .kv code . Here is my code and i am not able to figure out how to do it Can someone give advice ?

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button


class Container(AnchorLayout):
    def __init__(self, **kwargs):
        super(Container, self).__init__(**kwargs)

        btn = Button(text='Hello World',anchor_x='right',anchor_y='bottom')
        self.add_widget(btn)

        lbl = Label(text="Am i a Label ?",anchor_x='left',anchor_y='center')
        self.add_widget(lbl)


class MyJB(App):
    def build(self):

        parent = Container()

        return parent

if __name__ == '__main__':
    MyJB().run()
Foi útil?

Solução

The AnchorLayout aligns all widgets to a given point, not each widget to its own point. If you want widgets anchored in different locations, you need to use multiple AnchorLayouts. You also probably want to specify size and size_hint on either the AnchorLayout or the content widgets.

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button


class Container(FloatLayout):
    def __init__(self, **kwargs):
        super(Container, self).__init__(**kwargs)

        anchor_rb = AnchorLayout(anchor_x='right', anchor_y='bottom')
        btn = Button(text='Hello World', size=(100, 100), size_hint=(None, None))
        anchor_rb.add_widget(btn)
        self.add_widget(anchor_rb)

        anchor_lc = AnchorLayout(anchor_x='left', anchor_y='center')
        lbl = Label(text="Am i a Label ?", size=(100, 100), size_hint=(None, None))
        anchor_lc.add_widget(lbl)
        self.add_widget(anchor_lc)


class MyJB(App):
    def build(self):

        parent = Container()

        return parent

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

Personally, I find kv to be cleaner than manual widget creation, and it helps provide a definite separation between the UI and behavior.

kv version:

from kivy.app import App
from kivy.lang import Builder

root = Builder.load_string('''
FloatLayout:
    AnchorLayout:
        anchor_x: 'right'
        anchor_y: 'bottom'

        Button:
            text: 'Hello World'
            size: 100, 100
            size_hint: None, None

    AnchorLayout:
        anchor_x: 'left'
        anchor_y: 'center'

        Label:
            text: 'Am i a Label ?'
            size: 100, 100
            size_hint: None, None
''')

class MyJB(App):
    def build(self):
        return root

if __name__ == '__main__':
    MyJB().run()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top