Kivy – Line ”; Previous Next In the Kivy library, “Line” is an important vertex instruction in the “kivy.graphics” module. In Kivy, all the drawings are done on the Canvas associated with any of the available widgets. The Line instruction draws a line, or a sequence of lines as well as other shapes like rectangle, ellipse, Bezier, etc. It must be noted that the Kivy drawing instructions are not automatically relative to the position or size of the widget. On the contrary, the canvases of all the widgets share a common coordinate space. The Line function requires a list of numeric values. The interpretation of the numbers depends on the parameter to which this list is assigned. The parameters of List function are points, rectangle, ellipse, Bezier, etc. Draw a Rectangle Syntax You can draw a rectangle with Line function with the following syntax − with self.canvas: Line(rectangle=[x, y, w, h], width) Here, “x” and “y” represent the bottom-left position of the rectangle, and “w” and “h” represent the width and height. The line is automatically closed. You can also use a rounded_rectangle property to build a rectangle with round corners. The argument must be a tuple of one of the following forms − (x, y, width, height, corner_radius) (x, y, width, height, corner_radius, resolution) (x, y, width, height, corner_radius1, corner_radius2, corner_radius3, corner_radius4) (x, y, width, height, corner_radius1, corner_radius2, corner_radius3, corner_radius4, resolution) Example from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * from kivy.core.window import Window Window.size = (720,300) class drawRectangle(App): def build(self): widget = Widget() with widget.canvas: Color(1, 0, 1, 1) Line( rectangle=(50, 50, 300, 200), width=3 ) Line(rounded_rectangle=(500, 200, 300, 200, 20, 20, 20, 20)) return widget drawRectangle().run() Output It will produce the following output window − Draw an Ellipse You need to assign a list of numeric values to the ellipse property of the Line instruction. The value of ellipse argument must be a tuple of (x, y, width, height, angle_start, angle_end, segments) Where, “x” and “y” represent the bottom left of the ellipse “width” and “height” represent the size of the ellipse. If both these values are same, the result will be a circle “angle_start” and “angle_end” are in degree. The default value is 0 and 360. “segments” is the precision of the ellipse. You can use this property to create polygons with 3 or more sides. Values smaller than 3 will not be represented. Example In the code below, Line instruction is used to draw ellipse with different arguments − from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * from kivy.core.window import Window Window.size = (720,400) class drawEllipse(App): def build(self): widget = Widget() with widget.canvas: Color(0.5, .2, 0.4, 1) Line(ellipse=(500, 70, 200, 200), width=4) Line(ellipse=(100, 200, 100, 200), width=4) Color(.2, .8, 0, 1) Line(ellipse=(200, 100, 200, 100), width=4) Line(ellipse=(500, 300, 250, 90, 45, 270), width=3) Color(.1, .8, .3, 1) Line(ellipse=(200, 400, 200, 80, 180, 420, 30), width=5) return widget drawEllipse().run() Output Draw Bezier Curve A Bezier curve is weighted by some control points, that we include within the instruction. The Line() function accepts Bezier parameter to which a list of pairs of (x,y) coordinates are passed. The argument must be a list of 2n elements, “n” being the number of points. with self.canvas: Line(bezier=[x1, y1, x2, y2, x5, y3], width) It may be noted that the points parameter of Line instruction function also receives a similar set of 2n elements. The points property draws a line between successive points. with self.canvas: Line(points=[x1, y1, x2, y2, x5, y3], width) The point parameter to Line instruction only draws the points corresponding to each x-y coordinate pair, without any line connecting them. with self.canvas: Line(point=[x1, y1, x2, y2, x5, y3], width) Example The following code uses the same set of “x” and coordinate pairs to draw only the points, line, and a Bezier line − from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * from kivy.core.window import Window Window.size = (720, 400) class drawBezier(App): def build(self): widget = Widget() with widget.canvas: Color(0, 1, 1, 1) Bezier( points=[700, 400, 450, 300, 300, 350, 350, 200, 200, 100, 150, 10], segments=20 ) Color(1, 1, 0, 1) Point( points=[700, 400, 450, 300, 300, 350, 350, 200, 200, 100, 150, 10], pointsize=5 ) Color(.1, .1, .8) Line( points=[700, 400, 450, 300, 300, 350, 350, 200, 200, 100, 150, 10], pointsize=3 ) return widget drawBezier().run() Output When you run this code, it will produce an output window like the one shown here − It may be noted that Kivy provides another set of vertex instructions to draw these shapes with Rectangle, Ellipse, Bezier instructions. These are different from the rectangle, ellipse and bezier parameters to Line instruction. Note the uppercased first alphabets of instruction itself and parameter (Ellipse instruction vs. ellipse parameter of Line instruction). The Line function draws the shapes without recalculating the points. Print Page Previous Next Advertisements ”;
Category: kivy
Kivy – Bubble
Kivy – Bubble ”; Previous Next Kivy framework consists of a Bubble widget that acts as a small popup menu with an arrow on any one side of its contents. The direction of arrow can be configured as required. You can place it by setting its relative position of the “arrow_pos” property. Contents of the bubble are placed in a “BubbleContent” object, a subclass of BoxLayout. One or more BubbleButtons can be placed either horizontally or vertically. Although it is recommended use BubbleButtons, you can add any widget in the bubble”s content. The classes Bubble, BubbleContent, and BubbleButton are defined in kivy.uix.bubble module. from from kivy.uix.bubble import Bubble The following properties of the Bubble class help in customizing the appearance and behaviour of the Bubble menu − arrow_color − Arrow color, in the format (r, g, b, a). To use it you have to set arrow_image first, defaults to [1, 1, 1, 1]. arrow_image − Image of the arrow pointing to the bubble. arrow_margin − Automatically computed margin that the arrow widget occupies in x and y direction in pixel. arrow_pos − Specifies the position of the arrow as per one of the predefined values: left_top, left_mid, left_bottom top_left, top_mid, top_right right_top, right_mid, right_bottom bottom_left, bottom_mid, bottom_right. The default value is ”bottom_mid”. content − This is the object where the main content of the bubble is held. show_arrow − Indicates whether to show arrow. Default is True. BubbleButton − A button intended for use in a BubbleContent widget. Instead of this, you can use a “normal” button, but it will may look good unless the background is changed. BubbleContent − A styled BoxLayout that can be used as the content widget of a Bubble. The following schematic “kv” language script is used to build a simple Bubble object − Bubble: BubbleContent: BubbleButton: text: ”Button 1” BubbleButton: text: ”Button 2” Just as in case of a normal Button, we can bind a BubbleButton to a callback for its “on_press” event. Example When the following code is executed, it presents a normal button. When clicked, a Bubble menu pops up with three BubbleButtons. Each of these BubbleButtons invoke a pressed() callback method that reads the button”s caption and prints it on the console. We use the following “kv” language script to assemble the Bubble menu. A class named as “Choices” has been defined that subclasses the “kivy.uix.bubble.Bubble” class. class Choices(Bubble): def pressed(self, obj): print (“I like “, obj.text) self.clear_widgets() The class has pressed() instance method, invoked by each BubbleButton. Here is the “kv” script − <Choices> size_hint: (None, None) size: (300, 150) pos_hint: {”center_x”: .5, ”y”: .6} canvas: Color: rgb: (1,0,0) Rectangle: pos:self.pos size:self.size BubbleContent: BubbleButton: text: ”Cricket” size_hint_y: 1 on_press:root.pressed(self) BubbleButton: text: ”Tennis” size_hint_y: 1 on_press:root.pressed(self) BubbleButton: text: ”Hockey” size_hint_y: 1 on_press:root.pressed(self) BoxLayout widget acts as the root widget for the main application window and consists of a Button and a label. The “on_press” event invokes the “show_bubble()” method that pops up the bubble. class BubbleTest(FloatLayout): def __init__(self, **temp): super(BubbleTestApp, self).__init__(**temp) self.bubble_button = Button( text =”Your favourite Sport”, pos_hint={”center_x”:.5, ”center_y”:.5}, size_hint=(.3, .1),size=(300, 100) ) self.bubble_button.bind(on_release = self.show_bubble) self.add_widget(self.bubble_button) def show_bubble(self, *arg): self.obj_bub = Choices() self.add_widget(self.obj_bub) The driver App class code is as below − from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.bubble import Bubble from kivy.properties import ObjectProperty from kivy.core.window import Window Window.size = (720,400) class MybubbleApp(App): def build(self): return BubbleTest() MybubbleApp().run() Output The application shows a button at the center of the main window. When clicked, you should see the bubble menu above it. Every time you click any of the options in the bubble, the console shows the result, and hides the bubble. I like Tennis I like Hockey Print Page Previous Next Advertisements ”;
Kivy – Dropdown List
Kivy – Dropdown List ”; Previous Next A drop-down widget in Kivy is quite different from similar widgets in other GUI toolkits. Kivy”s dropdown shows not only labels, but any other widgets such as buttons, images, etc. The DropDown class is defined in the “kivy.uix.dropdown” module. from kivy.uix.dropdown import DropDown dropdown=DropDown() Following steps are required to construct a dropdown object − When adding other widgets in this object, we need to specify the height manually by disabling the size_hint, thereby the dropdown calculates the required area. For each of the child widgets added in DropDown, you need to attach a callback that will call the select() method on the dropdown. Bind each child and add to the drop down object. Add the dropdown to a main button and bind it with open() method of dropdown class Finally, run the app and click the main button. You will see a list of child widgets dropping down. Click on any of them to invoke its associated callback. Example In this example, we shall demonstrate how Drop Down widget in Kivy works. We shall add ten buttons to the dropdown with a for loop as shown below − dropdown = DropDown() for index in range(1, 11): btn = Button(text =”Button ”+str(index), size_hint_y = None, height = 40) btn.bind(on_release = lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) box.add_widget(dropdown) We place a main button in the BoxLayout, add the dropdown object to it, and bind the main button with open() method of dropdown object. box = BoxLayout(orientation=”vertical”) mainbutton = Button(text =”Drop Down Button”, size_hint=(None, None), size =(250, 75), pos_hint ={”center_x”:.5, ”top”:1}) box.add_widget(mainbutton) mainbutton.add_widget(dropdown) mainbutton.bind(on_release = dropdown.open) Finally, we need to listen for the selection in the dropdown list and assign the data to the button text. dropdown.bind(on_select = lambda instance, x: setattr(mainbutton, ”text”, x)) All these steps are included in the build() method of App class in the following code − from kivy.app import App from kivy.uix.dropdown import DropDown from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (720, 400) class Drop_down_app(App): def build(self): box = BoxLayout(orientation=”vertical”) mainbutton = Button( text=”Drop Down Button”, size_hint=(None, None), size=(250, 75), pos_hint={”center_x”: .5, ”top”: 1} ) box.add_widget(mainbutton) dropdown = DropDown() for index in range(1, 11): btn = Button(text=”Button ” + str(index), size_hint_y=None, height=40) btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) box.add_widget(dropdown) mainbutton.add_widget(dropdown) mainbutton.bind(on_release=dropdown.open) dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, ”text”, x)) return box Drop_down_app().run() Output When we run the above code, the main button is visible. Click the button. As a result, the list of buttons drop down. The caption of the main button will change to that of the button from the list when clicked. Print Page Previous Next Advertisements ”;
Kivy – Disabled Buttons
Kivy – Disabled Buttons ”; Previous Next The Kivy API has button widgets of different types. The objects of Button, ToggleButton, CheckBox are all buttons with different characteristics. There is one common attribute in all of them. They can accept and propagate the “touch” events on click events. All button objects can raise the button events, as these classes inherit the ButtonBehavior interface. You can make a button irresponsive to the button events by setting the “disabled” property to True. (The default value of disabled property is False. The disabled property is inherited from the Widget class.) from kivy.uix.button import Button b1 = Button(text=”OK”, disabled=True) In order to configure the appearance of a disabled button from a normal or enabled button, one can use the following properties − background_disabled_down − The background image of the button is a StringProperty, a string containing path to an image file and is used for the default graphical representation when the button is disabled and pressed. background_disabled_normal − Background image of the button is also an image path, used for the default graphical representation when the button is disabled and not pressed. disabled_color − This property is inherited from the Label class. It defines the color of the button text or caption when it is disabled. It”s a ColorProperty and defaults to [1,1,1,3] disabled_outline_color − This property defines the color of the text outline when the widget is disabled, in the (r, g, b) format. It is inherited from Label class. This feature requires the SDL2 text provider. The disabled_outline_color is a ColorProperty and defaults to [0, 0, 0]. Example The code given below arranges a ToggleButton and a normal Button in vertical BoxLayout. The toggle button changes the disabled property of the other button to True or False if its state is down or normal. from kivy.app import App from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout Window.size = (720, 350) class HelloApp(App): def on_button_press(self, instance, value): if value == ”down”: self.btn2.disabled = True self.btn2.text = ”Disabled” instance.text = ”Enable Btn 2” if value == ”normal”: self.btn2.disabled = False self.btn2.text = ”Enabled” instance.text = ”Disable Btn 2” def build(self): flo = BoxLayout(orientation=”vertical”) btn1 = ToggleButton( text=”Disable Btn 2”, font_size=40, size_hint=(1, .25), pos_hint={”center_x”: .5, ”center_y”: .8} ) btn1.bind(state=self.on_button_press) self.btn2 = Button( text=”Enabled”, color=[0, 0, 1, 1], disabled_color=[1, 0, 0, 1], font_size=40, size_hint=(1, .25), pos_hint={”center_x”: .5, ”center_y”: .2} ) flo.add_widget(btn1) flo.add_widget(self.btn2) return flo if __name__ == ”__main__”: HelloApp().run() Output When the program is run, it shows the button at the bottom (i.e., btn2) as enabled, with its caption in the Color property. As the button at the top (btn1) is pressed down, the one below becomes disabled, changing the color specified by the “disabled_color” property. Print Page Previous Next Advertisements ”;
Kivy – Console
Kivy – Console ”; Previous Next The Console tool in Kivy is similar to Inspector tool, with an additional featureprovision to add buttons and panels with the help of its addon architecture. Like the Inspector, the “kivy.modules.console” module has a command-line interface, as also an API for the tool to be used programmatically. In the command line usage, load the module with “-m” option of Python executable. python main.py -m console To activate the Kivy Console, call the create_console() function from the console module with the Window and the App object as arguments. You need to place the following statement in the build() method of the App class. from kivy.modules import console class Demo(App): def build(self): button = Button(text=”Test”) console.create_console(Window, self) return button Assume that you have developed a Kivy application with “slider.py” program that has the following interface. The app has three slider controls that help in changing the color of the text above. Add the call to the create_console() function (as described above) in the build() method of slider.py file and run it. To start with the above interface will be visible. Press ctrl+E to activate the Console tool. Following key combinations are defined − “Ctrl + e” − toggle console “Escape” − cancel widget lookup, then hide inspector view “Up” − select the parent widget “Down” − select the first child of the currently selected widget “Left” − select the previous sibling “Right” − select the next sibling When the console tool is activated, it shows a bar in the middle with Select, Properties and Tree buttons on left and a FPS button on the right. Click on the “Tree” button and you get a widget tree of the interface. Select the Slider control from the tree. Now press the Properties button. A scrollable list of all the properties of Slider widget will be available. Scroll down to the value property, and double click to get an editable box in which the current value is displayed, which you can change. Press escape to remove the console. You should see the Slider at the value set by you from the console. Addons One of the important features of the Console tool is the addon architecture which allows you to add buttons and panels to it. The addons activated by default are − ConsoleAddonFps − display the FPS at the top-right. ConsoleAddonSelect − activate the selection mode. ConsoleAddonBreadcrumb − display the hierarchy of the current widget at the bottom. ConsoleAddonWidgetTree − panel to display the widget tree of the application. ConsoleAddonWidgetPanel − panel to display the properties of the selected widget. To activate an addon, it must be added to Console.addons before the create_console is called. About Addon Let us add a About button the Console tool. It displays the object description including its ID in the console tool workspace in the middle. Add the following code in slider.py, before the definition of the App class − from kivy.modules.console import Console, ConsoleAddon, ConsoleLabel class ConsoleAddonAbout(ConsoleAddon): def init(self): self.console.add_panel( “About”, self.panel_activate, self.panel_deactivate ) def panel_activate(self): self.console.bind(widget=self.update_content) self.update_content() def panel_deactivate(self): self.console.unbind(widget=self.update_content) def deactivate(self): self.panel_deactivate() def update_content(self, *args): widget = self.console.widget if not widget: return text = “Selected widget is: {!r}”.format(widget) lbl = ConsoleLabel(text=text) self.console.set_content(lbl) Console.register_addon(ConsoleAddonAbout) If you run the slider.py script again, you get the About button added next to the Tree button. Locate the Slider from the widget tree and click on About button to show the object ID of the slider widget. Print Page Previous Next Advertisements ”;
Kivy – Language
Kivy – Language ”; Previous Next This chapter explains the important features, syntax and the usage of Kivy”s Design Language. The Kivy language (also know as “kv” Language) mainly describes the user interface of a Kivy app. It is similar to Qt”s QML. The rule definitions in the “kv” language are similar to CSS rules. Purpose The layout and placement of widgets in a Kivy app are coded into the build() method of Kivy”s App class. For applications with simpler user interface, this may work well. However, with the increasing complexity of the layout design, it quickly becomes too verbose and too difficult to maintain. Hence there is a need to separate the design part of the application from the processing logic. The “kv” language helps in achieving this separation of concerns. With the “kv” language script, you can create your widget tree in a declarative way and bind the widget properties to callbacks in a much more natural manner. One of the drawbacks of programmatically designing the interface is that the appearance cannot be viewed until the application is executed. On the other hand, the kviewer utility provides an interactive view of the design and placement of widgets, without having to load the script in the application. Loading the “kv” Script Once the design of widgets is finalized, it is loaded in the App class. This can be done in two ways. Using the Naming Convention Save the “kv” script with a “.kv” extension and its name corresponding to the name of App class. If the App class name ends with app keyword, it must be omitted. For example, if the App class is named as DemoApp as below, Class DemoApp(App): … … Then the kv file should be named as demo.kv. Kivy automatically loads the design into the build() method of the App class. If the kv file defines a root Widget, it will be attached to the App”s root attribute and used as the base of the application widget tree. Using the Builder Class If the name of the “kv” file doesn”t follow the above convention, the script can be loaded into the app with load_file() method of Loader class, which is available in the “kivy.lang” module. from kivy.app import App from kivy.lang import Builder Builder.load_file(”mykv.kv”) MydemoApp(App): def build(self): pass MydemoApp().run() You may also embed the entire “kv” language script as a string into the Python code and load it in the App class with Builder.load_string() method. from kivy.app import App from kivy.lang import Builder kv=””” #kv script goes here “”” MydemoApp(App): def build(self): Builder.load_string(kv) MydemoApp().run() The “kv” language has the following important elements − Rules − A rule in “kv” is similar to a CSS rule. It applies to specific widgets or classes inheriting the specified widget class. A “kv” rule can specify interactive behaviour or use them to add graphical representations of the widgets they apply to. root Widget − You can use the language to create your entire user interface. A “kv” file must contain only one root widget at most. Dynamic Classes − Dynamic classes let you create new widgets and rules on-the-fly, without any Python declaration. A kv script describes the content of a Widget. You can have one root rule, and any number of class or template rules. The root rule is declared by declaring the class of your root widget, without any indentation and followed by the “:” symbol. It sets the root attribute of the App instance. Widget: To declare a class rule, put the name of a widget class between “< >” and followed by the “:” symbol. It defines the appearance and behavior of any instance of that class − <MyWidget>: Kv language rules use indentation for delimitation, same as a Python source code. The thumb rule to remember is that with the angular brackets it”s a rule and without them, it”s a root widget. A schematic example − <MyClass>: prop1: value1 prop2: value2 canvas: CanvasInstruction1: canvasprop1: value1 CanvasInstruction2: canvasprop2: value2 AnotherClass: prop3: value1 There are three keywords specific to the “kv” language − self − always refer to the current widget. Button: text: ”My state is %s” % self.state root − refers to the base widget in the current rule and represents the root widget of the rule (the first instance of the rule) − <MyWidget>: custom: ”Hello world” Button: text: root.custom app − always refers to the instance of your application. Label: text: app.name The Kivy app window can contain only one widget as its root object. However, if you need to compose the app interface with more than one controls, you have to use the layout widget, and place multiple UX widgets in it and then put the layout as the root widget on the app window. The following “kv” file script defines a grid layout which can then be used with the App class − GridLayout: cols:1 Label: text:”Hello” font_size:100 color:(1,0,0,1) Button: text=”Ok” font_size:100 In the above case, the Label widget and a Button are placed in a one-column GridLayout. However, the objects and their properties cannot be accessed from within the Python code. To be able to do so, define the id property in the “kv” script. GridLayout: cols:1 Label: id:l1 text:”Hello” font_size:60 color:(1,0,0,1) Button: id:b1 text=”Ok” font_size:60 When this layout is loaded into the build() method, the App class can access the widget properties through this id. IT has a ids property which is a dictionary with id:value key-value pairs. print (self.ids.l1.text) Let us start with the kv script as follows, consisting of a label and a button in grid layout.
Kivy – Drawing App
Kivy – Drawing App ”; Previous Next In this chapter, we shall learn to develop a simple Kivy app that lets the user draw filled rectangles and circles (ellipses) of different dimensions and colors by dragging the mouse button. The user drags the mouse pointer from the top-left corner to the bottomdown corner of the intended rectangle/ellipse. The approach used in the development of the following code is to capture the mouse coordinates at the touch_down event and touch_up event. Hence we start the program with this code in the build() method of App class − def build(self): self.w= Widget() self.w.bind(on_touch_down=self.on_touch_down) self.w.bind(on_touch_up=self.on_touch_up) return(self.w) We want to let the user choose to draw a rectangle or a circle. Three toggle buttons for choosing to draw either, or clear the canvas have to be added. Hence, we change the layout of App window to box layout, adding the Widget object on top, and three buttons placed below it. lo = BoxLayout(orientation=”vertical”) self.w = Widget() self.w.bind(on_touch_down=self.on_touch_down) self.w.bind(on_touch_up=self.on_touch_up) lo.add_widget(self.w) hlo = BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b2 = ToggleButton(text=”Circle”, group=”mode”) self.b1 = ToggleButton(text=”Rectangle”, state=”down”, group=”mode”) self.b3 = ToggleButton(text=”Clear”, group=”mode”) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) return lo To draw the desired shape, we need to capture the mouse positions on touch down, and touch up. The on_touch_down() method is simple − def on_touch_down(self, *args): self.td = args[1].pos All the processing happens in on_touch_up() method. The captured coordinates of down event and up event are used to calculate the dimensionsof rectangle or circle. For circle, the x-radius, y-radius and the center are computed as follows − self.tu=args[1].pos xr = (self.tu[0]-self.td[0])/2 yr = (self.td[1]-self.tu[1])/2 c=(self.td[0]+xr, self.td[1]-yr) We need the width and height as well as the top-left corner coordinates for drawing rectangle. The self.td tuple gives top-left point, xr*2 gives the width and yr*2 gives the height. The shapes are drawn on the widget canvas. We choose a random color for drawing. The text property of the pressed button gives us the shape to be drawn − color = (random(), random(), random()) with self.w.canvas: Color(*color) if self.btn==”Rectangle”: Rectangle(pos=self.td, size=(xr*2,yr*2)) if self.btn==”Circle”: Ellipse(pos=(c), size=(xr,yr)) Three toggle buttons are bound to a method. If the caption is Clear, the widget canvas is cleared. def clear_canvas(self, instance, value): self.btn = instance.text self.press = True if value == ”down” and self.btn == ”Clear”: self.w.canvas.clear() return True Example The complete code for the app is given below − from random import random from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Color, Ellipse, Line, Rectangle from kivy.uix.togglebutton import ToggleButton from kivy.uix.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (720, 400) class MyPaintApp(App): def clear_canvas(self, instance, value): self.btn = instance.text self.press = True if value == ”down” and self.btn == ”Clear”: self.w.canvas.clear() return True def on_touch_down(self, *args): self.td = args[1].pos def on_touch_up(self, *args): if self.press == True: self.press = False return True self.tu = args[1].pos xr = (self.tu[0] – self.td[0]) / 2 yr = (self.td[1] – self.tu[1]) / 2 c = (self.td[0] + xr, self.td[1] – yr) color = (random(), random(), random()) with self.w.canvas: Color(*color) if self.btn == ”Rectangle”: Rectangle(pos=self.td, size=(xr * 2, yr * 2)) if self.btn == ”Circle”: Ellipse(pos=(c), size=(xr, yr)) def build(self): self.press = False self.btn = ”Rectangle” lo = BoxLayout(orientation=”vertical”) self.w = Widget() self.w.bind(on_touch_down=self.on_touch_down) self.w.bind(on_touch_up=self.on_touch_up) lo.add_widget(self.w) hlo = BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b2 = ToggleButton(text=”Circle”, group=”mode”) self.b1 = ToggleButton(text=”Rectangle”, state=”down”, group=”mode”) self.b3 = ToggleButton(text=”Clear”, group=”mode”) self.b1.bind(state=self.clear_canvas) self.b2.bind(state=self.clear_canvas) self.b3.bind(state=self.clear_canvas) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) return lo MyPaintApp().run() Output Run the above code. Choose the shape you want to draw. Drag the mouse from top-left to bottom-right. The rectangles/circles are drawn at drawn at different positions with random colors. Click the Clear button to clear the drawings on the canvas. Print Page Previous Next Advertisements ”;
Kivy – Data Loader
Kivy – Data Loader ”; Previous Next A Loader class in Kivy framework is an asynchronous data loader that makes it possible to load an image even if its data is not yet available. This feature is of particular use when you want to load image from an internet URL. The Loader class is defined in kivy.loader module. Typical use of Loader class is like this − from kivy.loader import Loader image = Loader.image(”http://mysite.com/test.png”) Use the loading_image property to specify a default image. Loader.loading_image = Image(default.png”) The Loader class is equipped with the following properties − error_image − Image used for error. For example − Loader.error_image = ”error.png” image(filename) − Load a image using the Loader. A ProxyImage is returned with a loading image. loading_image − Image used for loading. For example − Loader.loading_image = ”loading.png” max_upload_per_frame − The number of images to upload per frame. By default, we”ll upload only 2 images to the GPU per frame. num_workers − Number of workers to use while loading. This setting impacts the loader only on initialization. Once the loader is started, the setting has no impact. from kivy.loader import Loader Loader.num_workers = 4 The default value is “2” for giving a smooth user experience. ProxyImage() − Image returned by the Loader.image() function. proxyImage = Loader.image(“test.jpg”) pause() − Pause the loader. resume() − Resume the loader, after a pause(). run() − Main loop for the loader. start() − Start the loader thread/process. stop() − Stop the loader thread/process. The “on_load” event is fired when the image is loaded or changed. Similarly, the “on_error” is fired when the image cannot be loaded. “error: Exception data that occurred”. Example In the code given below, the Loader object loads an image from an internet URL. The ProxyImage object returned by the Loader binds to a method on its on_load event. The callback method uses its texture as the texture property of the Image object. from kivy.app import App from kivy.uix.image import Image from kivy.loader import Loader from kivy.core.window import Window Window.size = (720,400) class MyApp(App): title=”Loader” def _image_loaded(self, proxyImage): if proxyImage.image.texture: self.image.texture = proxyImage.image.texture def build(self): proxyImage = Loader.image(”https://source.unsplash.com/user/c_v_r/640×480”) proxyImage.bind(on_load=self._image_loaded) self.image = Image() return self.image MyApp().run() Output On execution, it will produce the following output − Print Page Previous Next Advertisements ”;
Kivy – Button Size
Kivy – Button Size ”; Previous Next It is important that a widget on a Kivy application”s user interface should be of an appropriate size. Just as the position property, the size property of the button (any widget for that matter) is governed by the layout in which it is placed. The button size can be configured by the two properties “size” and “size_hint”. The “kivy.uix.button.Button” class inherits these properties from the Widget class. The “size_hint” property of a button is a tuple of values used by its parent layout to decide the size. It defines the size relative to the layout”s size and not absolute size. For example − btn.size_hint = (w, h) Both the parameters “w” and “h” are specified as floating point numbers in the range 0 to 1. For example, 0.5 represents 50% and 1 represents 100%. # This button has width and height of the parent layout btn.size_hint=(1,1) # Width of this button will be half of the container”s width btn.size_hint=(0.5, 1) # This button will be of width and height 20% of the layout btn.size_hint=(.2,.2) On the other hand, the “size” property assigns the width and height of the button in absolute terms and expressed in units of pixels. btn.size=(200,100) However, for the button to be absolutely sized, you must ask Kivy layout to disregard the size hints. If you don”t want to use a size_hint for either the width or height, set the value to None. In other words, you must set “size_hint=(None, None)” before assigning size in absolute measurements. You can also set the size hints for width or height individually with “size_hint_x” and “size_hint_y” properties. Let us say you want to make a button that is 250px wide and 30% of the parent”s height btn.size_hint_x = None btn.size_hint_y= 0.3 widget.width = 250 These properties can also be set in the Button constructor arguments − btn = Button(text=”Hi there!”, size_hint=(None, 0.3), width=250) Example The following program places various buttons in a FloatLayout of the app window with different combinations of size_hint, size, pos_hint and pos properties − from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.core.window import Window Window.size = (720,400) class DemoApp(App): def build(self): f = FloatLayout() b1 = Button(text=”B1″, size_hint=(None, None)) f.add_widget(b1) b2 = Button(text=”B2″, size_hint=(1, None), height=20) f.add_widget(b2) b3 = Button(text=”B3″, size_hint=(None, None), pos=(0, 100), size=(400, 100)) f.add_widget(b3) b4 = Button(text=”B4”, size_hint=(None,.3), width=50, pos_hint={”x”:.6, ”y”:.2} ) f.add_widget(b4) b5 = Button(text=”B5”, size_hint=(None,.9), width=50, pos_hint={”x”:.5, ”y”:.5} ) f.add_widget(b5) return f if __name__ == ”__main__”: DemoApp().run() Output On running this code, you will get the following output window − Print Page Previous Next Advertisements ”;
Kivy – Button Colors
Kivy – Button Colors ”; Previous Next In any GUI application, button is an important component. Its primary function to respond to click event and invoke a callback. To design attractive GUI, the button color should be chosen appropriately. You can configure a button by specifying the color for its caption, background color in normal as well as disabled state. In Kivy, the Button class defines the following color-related properties − color background_color disabled_color outline_color disabled_outline_color color Property The Button class inherits this property from Label class, as Button is a Label that responds to click related events. The color property defines the color of the button text, or the button caption. Since color is of ColorProperty type, it must be specified in (r,g,b,a) format. The colors take the value between “0” to “1”. The “a” component is for transparency. For a button, color defaults to [1, 1, 1, 1]. background_color Property This acts as a multiplier to the texture colour. The default texture is grey, so just setting the background color will give a darker result. The background color of the button is a ColorProperty in the format (r, g, b, a) with default value [1,1,1,1]. disabled_color Property This property is inherited from the Label class. It defines the color of the button text or caption when it is disabled. It”s a ColorProperty and defaults to [1,1,1,3] outline_color Property Inherited from the Label class, this property configures the color of text outline. Note that this requires SDL2 text provider. This property is of ColorProperty type and its default value is [0,0,0,1] disabled_outline_color Property This property defines the color of the text outline when the widget is disabled, in the (r, g, b) format. It is inherited from Label class. This feature requires the SDL2 text provider. The disabled_outline_color is a ColorProperty and defaults to [0, 0, 0]. Example 1 Let us demonstrate the use of color and disabled_color properties. In the following example, we have placed two buttons in a floatlayout. They are instantiated with different color and disabled_color properties. When clicked, the text color changes. from kivy.app import App from kivy.uix.button import Button from kivy.config import Config from kivy.uix.floatlayout import FloatLayout # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”300”) Config.set(”graphics”, ”resizable”, ”1”) class HelloApp(App): def on_button_press(self, instance): instance.disabled = True def build(self): flo = FloatLayout() btn1 = Button(text= ”Hello Python”, color= [1,0,0,1], disabled_color = [0,0,1,1], font_size= 40, size_hint= (.4, .25), pos_hint= {”center_x”:.5, ”center_y”:.8}) btn1.bind(on_press = self.on_button_press) btn2 = Button(text= ”Hello Kivy”, color= [0,0,1,1], disabled_color = [1,0,0,1], font_size= 40, size_hint= (.4, .25), pos_hint= {”center_x”:.5, ”center_y”:.2}) flo.add_widget(btn1) btn2.bind(on_press = self.on_button_press) flo.add_widget(btn2) return flo if __name__ == ”__main__”: HelloApp().run() Output Initially, both the buttons are enabled. When you press the buttons, they get disabled (they are unable to receive the “on_press” event) and the text color changes as per the configuration. Example 2 In the following program, when any button is clicked, its text color and background color is interchanged. from kivy.app import App from kivy.uix.button import Button from kivy.config import Config from kivy.uix.floatlayout import FloatLayout # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”300”) Config.set(”graphics”, ”resizable”, ”1”) class HelloApp(App): def on_button_press(self, instance): print(“change color”) instance.background_color, instance.color = instance.color, instance.background_color def build(self): flo = FloatLayout() self.btn1 = Button(text=”Hello Python”, color=[1, 0, 0, 1], background_color=[0, 0, 1, 1], font_size=40, size_hint=(.4, .25), pos_hint={”center_x”: .5, ”center_y”: .8}) self.btn2 = Button(text=”Hello Kivy”, color=[0, 0, 1, 1], background_color=[1, 0, 0, 1], font_size=40, size_hint=(.4, .25), pos_hint={”center_x”: .5, ”center_y”: .2}) flo.add_widget(self.btn1) self.btn1.bind(on_press=self.on_button_press) self.btn2.bind(on_press=self.on_button_press) flo.add_widget(self.btn2) return flo if __name__ == ”__main__”: HelloApp().run() Output When you click any of the two buttons, their colors get interchanged as shown here − Print Page Previous Next Advertisements ”;