Book Image

Kivy: Interactive Applications in Python

By : Roberto Ulloa
4 (1)
Book Image

Kivy: Interactive Applications in Python

4 (1)
By: Roberto Ulloa

Overview of this book

Mobiles and tablets have brought with them a dramatic change in the utility of applications. Compatibility has become essential, and this has increased the kind of interaction that users expect: gestures, multi-touches, animations, and magic pens. Kivy is an open source Python solution that covers these market needs with an easy-to-learn and rapid development approach. Kivy is growing fast and gaining attention as an alternative to the established developing platforms. Kivy: Interactive Applications in Python quickly introduces you to the Kivy development methodology. You will learn some examples of how to use many of the Kivy components, as well as understand how to integrate and combine them into big projects. This book serves as a reference guide and is organized in such a way that once finished, you will have already completed your first project. You will start by learning the Kivy Language for building User Interfaces (UI) and vector figures. We then proceed to the uses of Kivy events and properties to glue the UI with the application logic. You then go on to build an entire User Interface (UI) starting from a hand-made sketch. Furthermore, you will go on to understand how to use the canvas and drawing instructions to create different types of geometrical figures. Finally, you will be introduced to a big set of interactive and smooth features: transformations (scale, rotate, and translate), gestures, animations, scheduling tasks, and multi-touch elements. Kivy: Interactive Applications in Python expands your knowledge by introducing various components that improve the User Experience (UX). Towards the end of the book, you will be confident to utilize Kivy components and strategies to start any application or game you have in mind.
Table of Contents (13 chapters)
Kivy: Interactive Applications in Python
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Layouts


No doubt that fixed coordinates are the most flexible way of organizing elements in an n-dimensional space; however, it is very time-consuming. Instead, Kivy provides a good set of layouts instead, which facilitate the work of organizing widgets. A Layout is a Widget subclass that implements different strategies to organize embedded widgets. For example, one strategy could be organizing widgets in a grid (GridLayout).

Let's start with a simple FloatLayout example. It works very similar to the way we organize widgets directly inside another Widget, except that now we can use proportional coordinates (proportions of the total size of the window) rather than fixed coordinates (exact pixels). This means that we don't need the calculations we did in the previous section with self and root. The following is the Python code:

68. # File name: floatlayout.py
69. 
70. from kivy.app import App
71. from kivy.uix.floatlayout import FloatLayout
72. 
73. class FloatLayoutApp(App):
74.   def build(self):
75.     return FloatLayout()
76. 
77. if __name__=="__main__":
78.   FloatLayoutApp().run()

There is nothing new in the preceding code (floatlayout.py) except for the use of FloatLayout (on line 75). The interesting parts are in the Kivy language (floatlayout.kv):

79. # File name: floatlayout.py
80. <Button>:
81.   color: .8,.9,0,1
82.   font_size: 32
83.   size_hint: .4, .3
84. 
85. <FloatLayout>:
86.   Button:
87.     text: 'Hello'
88.     pos_hint: {'x': 0, 'top': 1}
89.   Button:
90.     text: 'World!'
91.     pos_hint: {'right': 1, 'y': 0}

In the floatlayout.kv code file, we use two new properties, size_hint and pos_hint, which work with the proportional coordinates with values ranging from 0 to 1; (0, 0) is the bottom-left corner and (1, 1) the top-right corner. For example, the size_hint on line 83 sets the width to 40 percent of the current window width and the height to 30 percent of the current window height. Something similar happens to the pos_hint but the notation is different: a Python dictionary where the keys (for example, 'x' or 'top') indicate which part of the widget is referenced. For instance, 'x' is the left border. Notice that we use the top key instead of y in line 88 and right instead of x in line 91. The top and right properties respectively reference the top and right edges of the Button, so it makes the positioning simpler. That doesn't mean we could have used x and y for both the axes. For example, something like pos_hint: {'x': .85, 'y': 0} on line 91. The right and top keys avoids some calculations and makes the code clearer. The next screenshot illustrates the output of the previous code with the available keys for the pos_hint dictionary:

Using FloatLayout

The available pos_hint keys ( x, center_x, right, y , center_y, and top) are useful for aligning to edges or centering. For example, pos_hint: {'center_x':.5, 'center_y':.5} would align a Widget in the middle, no matter what the size of the window is.

Could have we used top and right with the fixed positioning of widgets2.kv (in line 64 and 67)? Yes, we could; but notice that pos doesn't accept Python dictionaries ({'x':0,'y':0}) that just lists of values (0,0). Therefore, instead of using the pos property, we have to use the x, center_x, right, y, center_y, and top properties directly. For example, instead of pos: root.x, root.top - self.height, we would have used the following code:

  x: 0
  top: root.height

Notice that these properties always specify fixed values (pixels) and not proportional ones.

Note

If we want to use proportional coordinates, we have to be inside a Layout (or an App), and use the pos_hint property.

If we are using a Layout instance, can we force the use of fixed values? Yes, but there can be conflicts if we are not careful with the properties we use. If we use any Layout, then pos_hint and size_hint will have the priority. If we want to use fixed positioning properties (pos, x, center_x, right, y, center_y, and top), we have to ensure that we are not using the pos_hint property. Secondly, if we want to use the size, height, or width properties, we need to give a None value to the size_hint axis we want to use with the absolute values. For example, size_hint: (None, .10) allows using the height property, but it keeps the width as 10 percent of the windows size. The following table summarizes everything we learned about the positioning and sizing properties. The first and second columns indicate the name of the property and its respective value. The third and fourth columns indicate if it is available for layouts and for widgets:

Property

Value

For layouts

For widgets

size_hint

A pair [w, h] where, w and h express a proportion (from 0 to 1 or None)

Yes

No

size_hint_x size_hint_y

A proportion from 0 to 1 or None indicating width (size_hint_x) or height (size_hint_y)

Yes

No

pos_hint

A dictionary with one x-axis key (x, center_x, or right) and one y-axis key (y, center_y, or top). The values are proportions from 0 to 1

Yes

No

size

A pair [w, h] where, w and h indicate fixed width and height in pixels

Yes, but set size_hint: (None, None)

Yes

width

A value indicating a fixed number of pixels

Yes, but set size_hint_x: None

Yes

height

A value indicating a fixed number of pixels

Yes, but set size_hint_y: None

Yes

pos

A pair [x, y] indicating a fixed coordinate (x, y) in pixels

Yes, but don't use pos_hint

Yes

x, right, or center_x

They have fixed number of pixels

Yes, but don't use x, right, or center_x in pos_hint

Yes

y, top, or center_y

The have fixed number of pixels

Yes, but don't use y, top, or center_y in pos_hint

Yes

We have to be careful because some of the properties behave different according to the layout we are using. Kivy currently has seven different layouts; six of them are briefly described in the following table. The left column shows the name of the Kivy Layout class and the right column describes briefly how they work:

Layout

Details

FloatLayout

This layout organizes the widgets with proportional coordinates with the size_hint and pos_hint properties. The values are numbers between 0 and 1 indicating a proportion to the window size.

RelativeLayout

This layout operates in the same way as FloatLayout does, but the positioning properties (pos, x, center_x, right, y, center_y, and top) are relative to the Layout size and not the window size.

GridLayout

This layout organizes widgets in a grid. You have to specify at least one of the two properties: cols (for columns) or rows (for rows).

BoxLayout

This layout organizes widgets in one row or one column depending whether the value of property orientation is horizontal or vertical.

StackLayout

This layout is similar to BoxLayout but it goes to the next row or column when it runs out of space. In this layout, there is more flexibility to set the orientation. For example, 'rl-bt' organizes the widgets in right-to-left and bottom-to-top order. Any combination of lr (left to right), rl (right to left), tb (top to bottom), and bt (bottom to top) is allowed.

AnchorLayout

This layout organizes the widgets to a border or to the center. The anchor_x property indicates the x position (left, center or right), whereas anchor_y indicates the y position (top, center or bottom)

The seventh layout, which is the ScatterLayout, works similar to RelativeLayout but it allows multitouch gesturing for rotating, scaling, and translating. It is slightly different in its implementation so we will review it later. The Kivy API (http://kivy.org/docs/api-kivy.html) offers a detailed explanation and good examples on each of them. The behavioral difference of the properties depending on the Layout is sometimes unexpected but the following are some of the hints that will help you in the GUI building process:

  • The size_hint, size_hint_x, and size_hint_y properties work on all the layouts but the behavior might be different. For example, GridLayout will try to take an average of the x hints and y hints on the same row or column respectively.

  • It is advisable to use values from 0 to 1 with the size_hint, size_hint_x, and size_hint_y properties. However, you can also use values bigger than 1. Depending on the Layout, Kivy makes the Button bigger than the container or tries to recalculate a proportion based on the sum of the hints on the same axis.

  • The pos_hint property works only in FloatLayout, RelativeLayout, and BoxLayout. In BoxLayout, only the x keys (x, center_x, and right) work in the vertical orientation and vice versa. An analogous rule applies for the fixed positioning properties (pos, x, center_x, right, y, center_y, and top).

  • The size_hint , size_hint_x, and size_hint_y properties can always be set as None in favor of size, width, and height.

There are more properties and particularities of each Layout, but with the ones we have covered, you will be able to build almost any GUI you desire. In general, the recommendation is to use the layout as it is. Don't try to force the layout through an odd configuration of properties. Instead, it is better to use more layouts and embed them to reach our design goals. In the next section, we will teach you how to embed layouts, and we will offer a more comprehensive example of them.