Kivy box layout

Kivy box layout DEFAULT

Box Layout¶

_images/boxlayout.gif

arranges children in a vertical or horizontal box.

To position widgets above/below each other, use a vertical BoxLayout:

layout=BoxLayout(orientation='vertical')btn1=Button(text='Hello')btn2=Button(text='World')layout.add_widget(btn1)layout.add_widget(btn2)

To position widgets next to each other, use a horizontal BoxLayout. In this example, we use 10 pixel spacing between children; the first button covers 70% of the horizontal space, the second covers 30%:

layout=BoxLayout(spacing=10)btn1=Button(text='Hello',size_hint=(.7,1))btn2=Button(text='World',size_hint=(.3,1))layout.add_widget(btn1)layout.add_widget(btn2)

Position hints are partially working, depending on the orientation:

  • If the orientation is vertical: x, right and center_x will be used.

  • If the orientation is horizontal: y, top and center_y will be used.

Kv Example:

BoxLayout:orientation:'vertical'Label:text:'this on top'Label:text:'this right aligned'size_hint_x:Nonesize:self.texture_sizepos_hint:{'right':1}Label:text:'this on bottom'

You can check the examples/widgets/boxlayout_poshint.py for a live example.

Note

The size_hint uses the available space after subtracting all the fixed-size widgets. For example, if you have a layout that is 800px wide, and add three buttons like this:

btn1=Button(text='Hello',size=(200,100),size_hint=(None,None))btn2=Button(text='Kivy',size_hint=(.5,1))btn3=Button(text='World',size_hint=(.5,1))

The first button will be 200px wide as specified, the second and third will be 300px each, e.g. (800-200) * 0.5

Changed in version 1.4.1: Added support for pos_hint.

class (**kwargs)[source]¶

Bases:

Box layout class. See module documentation for more information.

(widget, index=0, canvas=None)[source]¶

Add a new widget as a child of this widget.

Parameters
widget:

Widget to add to our list of children.

index: int, defaults to 0

Index to insert the widget in the list. Notice that the default of 0 means the widget is inserted at the beginning of the list and will thus be drawn on top of other sibling widgets. For a full discussion of the index and widget hierarchy, please see the Widgets Programming Guide.

canvas: str, defaults to None

Canvas to add widget’s canvas to. Can be ‘before’, ‘after’ or None for the default canvas.

>>> fromkivy.uix.buttonimportButton>>> fromkivy.uix.sliderimportSlider>>> root=Widget()>>> root.add_widget(Button())>>> slider=Slider()>>> root.add_widget(slider)
(*largs)[source]¶

This function is called when a layout is called by a trigger. If you are writing a new Layout subclass, don’t call this function directly but use instead.

The function is by default called before the next frame, therefore the layout isn’t updated immediately. Anything depending on the positions of e.g. children should be scheduled for the next frame.

Automatically computed minimum height needed to contain all children.

is a and defaults to 0. It is read only.

Automatically computed minimum size needed to contain all children.

is a of (, ) properties. It is read only.

Automatically computed minimum width needed to contain all children.

is a and defaults to 0. It is read only.

Orientation of the layout.

is an and defaults to ‘horizontal’. Can be ‘vertical’ or ‘horizontal’.

Padding between layout box and children: [padding_left, padding_top, padding_right, padding_bottom].

padding also accepts a two argument form [padding_horizontal, padding_vertical] and a one argument form [padding].

Changed in version 1.7.0: Replaced NumericProperty with VariableListProperty.

is a and defaults to [0, 0, 0, 0].

(widget)[source]¶

Remove a widget from the children of this widget.

Parameters
widget:

Widget to remove from our children list.

>>> fromkivy.uix.buttonimportButton>>> root=Widget()>>> button=Button()>>> root.add_widget(button)>>> root.remove_widget(button)

Spacing between children, in pixels.

is a and defaults to 0.

Sours: https://kivy.org/doc/stable/api-kivy.uix.boxlayout.html

Source code for kivy.uix.boxlayout

'''Box Layout==========.. only:: html .. image:: images/boxlayout.gif :align: right.. only:: latex .. image:: images/boxlayout.png :align: right:class:`BoxLayout` arranges children in a vertical or horizontal box.To position widgets above/below each other, use a vertical BoxLayout:: layout = BoxLayout(orientation='vertical') btn1 = Button(text='Hello') btn2 = Button(text='World') layout.add_widget(btn1) layout.add_widget(btn2)To position widgets next to each other, use a horizontal BoxLayout. In thisexample, we use 10 pixel spacing between children; the first button covers70% of the horizontal space, the second covers 30%:: layout = BoxLayout(spacing=10) btn1 = Button(text='Hello', size_hint=(.7, 1)) btn2 = Button(text='World', size_hint=(.3, 1)) layout.add_widget(btn1) layout.add_widget(btn2)Position hints are partially working, depending on the orientation:* If the orientation is `vertical`: `x`, `right` and `center_x` will be used.* If the orientation is `horizontal`: `y`, `top` and `center_y` will be used.Kv Example:: BoxLayout: orientation: 'vertical' Label: text: 'this on top' Label: text: 'this right aligned' size_hint_x: None size: self.texture_size pos_hint: {'right': 1} Label: text: 'this on bottom'You can check the `examples/widgets/boxlayout_poshint.py` for a live example... note:: The `size_hint` uses the available space after subtracting all the fixed-size widgets. For example, if you have a layout that is 800px wide, and add three buttons like this:: btn1 = Button(text='Hello', size=(200, 100), size_hint=(None, None)) btn2 = Button(text='Kivy', size_hint=(.5, 1)) btn3 = Button(text='World', size_hint=(.5, 1)) The first button will be 200px wide as specified, the second and third will be 300px each, e.g. (800-200) * 0.5.. versionchanged:: 1.4.1 Added support for `pos_hint`.'''__all__=('BoxLayout',)fromkivy.uix.layoutimportLayoutfromkivy.propertiesimport(NumericProperty,OptionProperty,VariableListProperty,ReferenceListProperty)
[docs]classBoxLayout(Layout):'''Box layout class. See module documentation for more information. '''spacing=NumericProperty(0)'''Spacing between children, in pixels. :attr:`spacing` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. '''padding=VariableListProperty([0,0,0,0])'''Padding between layout box and children: [padding_left, padding_top, padding_right, padding_bottom]. padding also accepts a two argument form [padding_horizontal, padding_vertical] and a one argument form [padding]. .. versionchanged:: 1.7.0 Replaced NumericProperty with VariableListProperty. :attr:`padding` is a :class:`~kivy.properties.VariableListProperty` and defaults to [0, 0, 0, 0]. '''orientation=OptionProperty('horizontal',options=('horizontal','vertical'))'''Orientation of the layout. :attr:`orientation` is an :class:`~kivy.properties.OptionProperty` and defaults to 'horizontal'. Can be 'vertical' or 'horizontal'. '''minimum_width=NumericProperty(0)'''Automatically computed minimum width needed to contain all children. .. versionadded:: 1.10.0 :attr:`minimum_width` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. It is read only. '''minimum_height=NumericProperty(0)'''Automatically computed minimum height needed to contain all children. .. versionadded:: 1.10.0 :attr:`minimum_height` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. It is read only. '''minimum_size=ReferenceListProperty(minimum_width,minimum_height)'''Automatically computed minimum size needed to contain all children. .. versionadded:: 1.10.0 :attr:`minimum_size` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`minimum_width`, :attr:`minimum_height`) properties. It is read only. '''def__init__(self,**kwargs):super(BoxLayout,self).__init__(**kwargs)update=self._trigger_layoutfbind=self.fbindfbind('spacing',update)fbind('padding',update)fbind('children',update)fbind('orientation',update)fbind('parent',update)fbind('size',update)fbind('pos',update)def_iterate_layout(self,sizes):# optimize layout by preventing looking at the same attribute in a looplen_children=len(sizes)padding_left,padding_top,padding_right,padding_bottom=self.paddingspacing=self.spacingorientation=self.orientationpadding_x=padding_left+padding_rightpadding_y=padding_top+padding_bottom# calculate maximum space used by size_hintstretch_sum=0.has_bound=Falsehint=[None]*len_children# min size from all the None hint, and from those with sh_minminimum_size_bounded=0iforientation=='horizontal':minimum_size_y=0minimum_size_none=padding_x+spacing*(len_children-1)fori,((w,h),(shw,shh),_,(shw_min,shh_min),(shw_max,_))inenumerate(sizes):ifshwisNone:minimum_size_none+=welse:hint[i]=shwifshw_min:has_bound=Trueminimum_size_bounded+=shw_minelifshw_maxisnotNone:has_bound=Truestretch_sum+=shwifshhisNone:minimum_size_y=max(minimum_size_y,h)elifshh_min:minimum_size_y=max(minimum_size_y,shh_min)minimum_size_x=minimum_size_bounded+minimum_size_noneminimum_size_y+=padding_yelse:minimum_size_x=0minimum_size_none=padding_y+spacing*(len_children-1)fori,((w,h),(shw,shh),_,(shw_min,shh_min),(_,shh_max))inenumerate(sizes):ifshhisNone:minimum_size_none+=helse:hint[i]=shhifshh_min:has_bound=Trueminimum_size_bounded+=shh_minelifshh_maxisnotNone:has_bound=Truestretch_sum+=shhifshwisNone:minimum_size_x=max(minimum_size_x,w)elifshw_min:minimum_size_x=max(minimum_size_x,shw_min)minimum_size_y=minimum_size_bounded+minimum_size_noneminimum_size_x+=padding_xself.minimum_size=minimum_size_x,minimum_size_y# do not move the w/h get above, it's likely to change on above lineselfx=self.xselfy=self.yiforientation=='horizontal':stretch_space=max(0.0,self.width-minimum_size_none)dim=0else:stretch_space=max(0.0,self.height-minimum_size_none)dim=1ifhas_bound:# make sure the size_hint_min/max are not violatedifstretch_space<1e-9:# there's no space, so just set to min size or zerostretch_sum=stretch_space=1.fori,valinenumerate(sizes):sh=val[1][dim]ifshisNone:continuesh_min=val[3][dim]ifsh_minisnotNone:hint[i]=sh_minelse:hint[i]=0.# everything else is zeroelse:# hint gets updated in placeself.layout_hint_with_bounds(stretch_sum,stretch_space,minimum_size_bounded,(val[3][dim]forvalinsizes),(elem[4][dim]foreleminsizes),hint)iforientation=='horizontal':x=padding_left+selfxsize_y=self.height-padding_yfori,(sh,((w,h),(_,shh),pos_hint,_,_))inenumerate(zip(reversed(hint),reversed(sizes))):cy=selfy+padding_bottomifsh:w=max(0.,stretch_space*sh/stretch_sum)ifshh:h=max(0,shh*size_y)forkey,valueinpos_hint.items():posy=value*size_yifkey=='y':cy+=posyelifkey=='top':cy+=posy-helifkey=='center_y':cy+=posy-(h/2.)yieldlen_children-i-1,x,cy,w,hx+=w+spacingelse:y=padding_bottom+selfysize_x=self.width-padding_xfori,(sh,((w,h),(shw,_),pos_hint,_,_))inenumerate(zip(hint,sizes)):cx=selfx+padding_leftifsh:h=max(0.,stretch_space*sh/stretch_sum)ifshw:w=max(0,shw*size_x)forkey,valueinpos_hint.items():posx=value*size_xifkey=='x':cx+=posxelifkey=='right':cx+=posx-welifkey=='center_x':cx+=posx-(w/2.)yieldi,cx,y,w,hy+=h+spacing

[docs]defdo_layout(self,*largs):children=self.childrenifnotchildren:l,t,r,b=self.paddingself.minimum_size=l+r,t+breturnfori,x,y,w,hinself._iterate_layout([(c.size,c.size_hint,c.pos_hint,c.size_hint_min,c.size_hint_max)forcinchildren]):c=children[i]c.pos=x,yshw,shh=c.size_hintifshwisNone:ifshhisnotNone:c.height=helse:ifshhisNone:c.width=welse:c.size=(w,h)

[docs]defadd_widget(self,widget,index=0,canvas=None):widget.fbind('pos_hint',self._trigger_layout)returnsuper(BoxLayout,self).add_widget(widget,index,canvas)

[docs]defremove_widget(self,widget):widget.funbind('pos_hint',self._trigger_layout)returnsuper(BoxLayout,self).remove_widget(widget)

Sours: https://kivy.org/doc/stable/_modules/kivy/uix/boxlayout.html
  1. Watcher on ebay
  2. Torch e5t
  3. Macbook desk mockup

Box Layout In Kivy With Example

# Sample Kivy app demonstrating the working of Box layout

 

# imports

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button

 

# Boxlayout is the App class

class BoxLayoutDemo(App):

    def build(self):

        superBox        = BoxLayout(orientation='vertical')

   

        horizontalBox   = BoxLayout(orientation='horizontal')

        button1         = Button(text="One")

        button2         = Button(text="Two")

 

        horizontalBox.add_widget(button1)

        horizontalBox.add_widget(button2)

   

        verticalBox     = BoxLayout(orientation='vertical')

        button3         = Button(text="Three")

        button4         = Button(text="Four")

 

        verticalBox.add_widget(button3)

        verticalBox.add_widget(button4)

   

        superBox.add_widget(horizontalBox)

        superBox.add_widget(verticalBox)

   

        return superBox

   

 

# Instantiate and run the kivy app

if __name__ == '__main__':

    BoxLayoutDemo().run()

 

Sours: https://pythontic.com/app/kivy/box%20layout
Kivy BoxLayout in Hindi - kivy full course in Hindi - python kivy tutorial in Hindi

website logoYasoob Khalid

This was a guest post by Mike Driscoll.

Recently I’ve started learning about Kivy, a Python Natural User Interface (NUI) toolkit. As I understand it, Kivy is kind of a spiritual successor to pyMT, which you can read more about here. In this article, we will be learning how Kivy handles layout management. While you can position widgets using x/y coordinates, in every GUI toolkit I’ve used, it’s almost always better to use some kind of layout management that the toolkit provides. This allows the widgets to resize and move appropriately as the user changes the window’s size. In Kivy, these things Layouts. If you’ve used wxPython, they are analogous to wxPython’s sizers.

I should also note that Kivy can do layouts in two different ways. The first way is to do Layouts with Python code only. The second way is to use a mixture of Python and Kv language. This is to promote the model-view-controller way of doing things. It looks kind of like CSS and reminds me a little of wxPython and XRC. We will look at how to use both methods in this article. While Kivy supports multiple types of Layouts, this article will be focusing only on the BoxLayout. We will show how to nest BoxLayouts.

Kivy, Python and BoxLayout

Kivy hbox

Creating a BoxLayout in Kivy using Python is actually pretty easy and quite intuitive. We’ll start out with a code example and then follow the code with an explanation. Let’s get started!

Here we have created a vertically oriented BoxLayout class and a horizontally oriented BoxLayout class. Each class contains 5 buttons with random background colors. The colors follow RGBA, but can have individual values that are between zero and one. Oddly enough, if you use numbers greater than one, the color becomes brighter. I happened to use 255 instead of 1 when I created the screenshot above, so if you happen to run this code and see a more muted set of colors, that’s why.

To make the examples extremely simple, we only import Kivy’s App, Button and BoxLayout classes. The BoxLayout class accepts several arguments, but we’ll focus on the following 3: orientation, padding and spacing. Because BoxLayout is a sub-class of Layout and Widget, it inherits many other methods and keyword arguments that are not covered here. But back to the arguments we currently care about. The padding argument tells Kivy how much space there should be between the Layout and its children, whereas the spacing arguments tells it how much spacing there should be between the children.

To create the buttons, we use a simple loop that loops over a small range of numbers. Each iteration creates a button with a random background color and adds that button to the Layout instance. Then we return the layout at the end.

The vertical BoxLayout example in the VBoxLayoutExample class is slightly different in that I thought it would be fun to be able to set the orientation programmatically. The code is pretty much the same except that I added a setOrientation method. Note that if you call setOrientation again, it will have no effect. As one of my commenters so kindly pointed out, you would need to bind the orientation to the App orient property or use the Kv language to achieve this.

If you comment out the call to HBoxLayoutExample at the end of the script and un-comment out the other two lines, then you should end up seeing something like this:

Kivy vbox

Notice that when you don’t set a background color, Kivy defaults to a dark grey. Kivy does not try to look like a native application. This may or may not be a big deal to you depending on what sort of program you’re trying to achieve, but it should be noted. Now we’re ready to learn about nesting!

Nesting BoxLayouts

kv nested box

Nesting BoxLayouts inside of each other is pretty easy with Kivy too. Whenever you go to create an application with a complicated interface that will need nested sizers, you should take some time to sketch the layout out with pencil and paper. Then you can draw boxes around the widgets in different ways to help you visualize which Layouts you’ll need and how to nest them in each other. I have found this quite helpful with wxPython and I think it applies to any other GUI toolkit that doesn’t have a WYSIWYG editor. By the way, BoxLayouts are very powerful. If you know what you’re doing, you can make just about any interface with them alone just be using clever nesting.

Enough talk, let’s look at some code!

This example is very similar to the last one. The devil is in the details though. Here we have a nested for loop that creates 3 BoxLayouts that contain 5 buttons a piece. Each Layout is then inserted into the top level Layout at the end of each iteration in the outside loop. In case you missed it, scroll back up to see how it turned out. The trick is to create one top-level or main Layout and add other Layouts to it. Now let’s turn our attention to learning how to do these things with the Kv language.

Kv+Python and BoxLayout

kv vbox

It’s almost always a little painful to learn a new language. Fortunately, the Kv language actually follows Python pretty closely, including Python’s requirement of using indentation levels to denote when a section of code begins and ends. You may want to spend a few minutes reading about the Kv language on the Kivy website. Whenever you’re ready, we can continue. First we’ll start off with the Python code:

This code is much simpler than our previous examples, but it’s also rather mysterious. First of all, we create an empty sub-class of BoxLayout. Then we create our App class which has a build method that just returns an instance of the empty BoxLayout class. What’s going on here? Well we have to look at the Kv file to find out!

When you save the code above, you’ll have to name it to be the same as the App class, but with a .kv instead of a .py and in lowercase. That means the name of this Kv file needs to be kvboxlayout.kv. You will note that you also need to strip off the App part of the class name such that KVBoxLayoutApp becomes kvboxlayout. Yes, it’s a little confusing. If you don’t follow the naming conventions correctly, the file will run but you will have an empty black window.

Anyway, first off in the Kv file, we have a section that starts with :. This tells Kivy that we are sub-classing the Button class and calling our sub-class MyButton. Then we indent the required four spaces and set the button’s label color and font size. Next we create a BoxLayout section. Notice that we didn’t create a sub-class this time. Then we tell it what orientation it should be and add 5 MyButton instances, each one having its own individual label and color.

One of the core Kivy developers pointed out that by creating the BoxLayout in this manner, I am redefining the BoxLayout for all usages. This is not a good thing, even if it does make the example simpler. Thus in the next example, we’ll stop doing that and do it the right way instead!

Nesting BoxLayouts with Kv

Nested box

Nesting BoxLayouts in Kv is a little confusing at first, but once you get the hang of it, you’ll find that it’s really quite easy. We’ll start out with the Python code, take a look at how it works and then look at the Kv code.

This time around, we need to create two generic Widget classes: HBoxWidget and VBoxWidget. These are actually dummy classes that become BoxLayouts in the Kv code. Speaking of which, let’s take a look at that now. Note that you’ll need to name the Kv file kvnestedboxlayout.kv, which you’ll note, is a lowercase version of KVNestedBoxLayoutApp.

The button code is the same as before. Next we have the HBoxWidget which we define as a horizontal BoxLayout with 5 buttons in it. Then we create an instance of VBoxWidget that is a vertical BoxLayout, but this Layout contains two instances of the HBoxWidget. You’ll note that in the Python code’s build method, we are returning the VBoxWidget, so that’s where the action is. If you remove those two HBoxWidget calls, the result will be an empty black window.

There is another way to use Kv files in Kivy. It is through the kivy.lang.Builder.load_file (or load_string) API, which gives you the ability to load Kv files without needing to remember to name the Kv file in some special way. You can read about the API on their website and see an example of it in action in the Kivy examples on github. The only caveat to using this method is that you need to be careful not to load the same file twice or your UI may get messed up.

Wrapping Up

This just scratches the surface of Kivy’s Layout system. There are 6 other Layout types available. However, I think you’ll find that the examples in this article will get you started down the road of successfully creating cool Kivy applications of your very own. If you need help learning Kivy, there’s a pretty good set of documentation on their website. They also have a Google Group and a #kivy channel on freenode.

Related Readings

Download the Source

Note: This is an official cross-posting of an article from the Mouse Vs Python blog. You can read the original here.

Sours: https://yasoob.me/2013/12/02/kivy-101-how-to-use-boxlayouts/

Layout kivy box

Turning in different directions, I was able to examine it from all sides. I am not a lot aroused, but for me it is difficult to identify. Although it was obvious that the lady liked to show herself and be proud. Of her forms. Meeting my eyes, I noticed that the lady was excited and she could hardly restrain herself and her emotions.

Kivy Crash Course #4 - Layout Management Complete Example

And then another one. Thank you, Dr. Bale. Stephanies face lit up with a smile of gratitude.

Similar news:

Natasha, without thinking twice, deciding to take the bull by the horns and other parts of the body, climbed onto the. Sofa and threw her leg over the man. Hanging over his erect penis, she aimed at him with her crotch and, slightly spreading her lips, began to sit on him. He seemed warm and pleasant to her, but not hot as yesterday, and at the same time, habitually large.

Therefore, sitting down on it halfway, the woman stopped and began to gently move up and down on it.



16216 16217 16218 16219 16220