Kivy – Splitter ”; Previous Next The Splitter widget in Kivy puts a draggable boundary around any other widget or a layout contained in it. You can drag the boundary to resize the size of the object enclosed in it. The boundary can be placed to the top or bottom, or to the left or right of the enclosed widget. The Splitter class is defined in the “kivy.uix.splitter” module. from kivy.uix.splitter import Splitter split = Splitter(**kwargs) One of the important properties required to configure the placement of boundary is ”sizable_from”. It defines Specifies from which direction the widget is resizable. Options are: left, right, top or bottom; the default being ”left”. The boundary has a grip in the middle. You can drag the boundary with this grip or even by double-clicking it. Other properties of the Splitter class are as follows − border − Border used for the BorderImage graphics instruction. This must be a list of four values: (bottom, right, top, left) and default is [4,4,4,4] keep_within_parent − If True, it will limit the splitter to stay within its parent widget. max_size − Specifies the maximum size beyond which the widget is not resizable. max_size defaults to 500pt. min_size − Specifies the minimum size beyond which the widget is not resizable. Defaults to 100 pt. rescale_with_parent − If True, will automatically change size to take up the same proportion of the parent widget when it is resized, while staying within min_size and max_size. sizable_from − Specifies whether the widget is resizable. Options are − left, right, top or bottom; defaults to left. Example Let us create a simple horizontal box layout and place an Image widget in between two buttons. The Image object however, is placed inside a Splitter, resizable from the left. from kivy.app import App from kivy.uix.button import Button from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.splitter import Splitter from kivy.core.window import Window Window.size = (720,350) class splitterApp(App): def build(self): layout=BoxLayout(orientation=”horizontal”) b1=Button( text=”Button1”, font_size=24, color=(1,0,0,1) ) layout.add_widget(b1) spl=Splitter(sizable_from = ”left”) img=Image(source=”Logo.jpg”) spl.add_widget(img) layout.add_widget(spl) b2=Button( text=”Button 2”, font_size=24, background_color =(.8, .4, .3, 1) ) layout.add_widget(b2) return layout splitterApp().run() Output As the program is run, you will see a dragable boundary with grip towards the left of the image. Drag it to resize the image. Here is the “kv” script version of program to demonstrate the use of a vertical splitter, sizable from bottom. BoxLayout: orientation:”vertical” Button: text: ”Button 1” font_size:24 color:(1,0,0,1) Splitter: sizable_from : ”bottom” Image: source:”Logo.jpg” Button: text:”Button 2” font_size:24 background_color: (.8, .4, .3, 1) The vertically resizable image widget appears as shown below − Print Page Previous Next Advertisements ”;
Category: kivy
Kivy – Button Position
Kivy – Button Position ”; Previous Next Placing the widgets at their appropriate positions is the key to design an ergonomic user interface. In Kivy, the positioning of buttons (as also the other widgets) is largely controlled by the layouts used. In this chapter, we shall learn how to place a button at a certain position on a Kivy application window. The first factor that decides the positioning is the layout. In Kivy, layouts are the containers used to arrange widgets in a particular manner. For example − A BoxLyout places the widgets sequentially, either in vertical or horizontal order. If you use GridLayout, the widget position is decided by the rows and cols properties. A FloatLayout puts no restrictions on placement. You can put a button or any other widget at any position by assigning its absolute coordinates. Window size To place a button at a certain position, we first define the size of the application window. The “size” property of Window object helps you to set the desired size. from kivy.core.window import Window Window.size = (720,400) Kivy”s window coordinate system defines the position of widgets and touch events dispatched to them. It places (0, 0) at the bottom left corner of the window. Obviously, the top-right corner of the window corresponds to (1,1). The Button class inherits “pos” and “pos_hint” properties from the Widget class. They help in determining the position of button on the window surface. Position properties pos − This property is a tuple of coordinate values “x” and “y” along the horizontal and vertical axis, measured from the bottom-left corner of the window. For example − button = Button(text =”Hello world”, pos =(20, 20)) pos_hint − This property provides a hint for the position of a widget. It allows you to set the position of the widget inside its parent layout. The property is a dictionary of upto 8 keys determining the position − x y left right top bottom center_x center_y The keys ”x”, ”right” and ”center_x” will use the parent width. The keys ”y”, ”top” and ”center_y” will use the parent height. For example, if you want to set the top of the button to be at 10% height of its parent layout, you can write − button = Button(text =”Hello world”, pos_hint={”top”: 0.1}) “pos_hint” is an ObjectProperty. is not used by all layouts. Layouts supporting positioning FloatLayout − Supports “pos_hint” properties. The values are numbers between 0 and 1 indicating a proportion to the window size. RelativeLayout − The positioning properties (pos, x, center_x, right, y, center_y, and top) are relative to the Layout size and not the window size. BoxLayout − only the “x” keys (x, center_x, and right) work in the vertical orientation and (y, center_y,top) in horizontal orientation. An same rule applies for the fixed positioning properties (pos, x, center_x, right, y, center_y, and top). In the code below, we have placed a horizontal BoxLayout and a FloatLayout inside the upper vertical BoxLayout. The upper horizontal box houses four buttons: LEFT, RIGHT, TOP and BOTTOM. Inside the FloatLaout, we have a button placed with “pos” properties. The App class has one method called movebtn() which identifies the caption of the button pressed and changes the “x” or “y” position of the button def movebtn(self,instance): if instance.text ==”RIGHT”: self.btn.pos[0]=self.btn.pos[0]+10 if instance.text == ”LEFT”: self.btn.pos[0] = self.btn.pos[0]-10 if instance.text == ”UP”: self.btn.pos[1] = self.btn.pos[1]+10 if instance.text == ”DOWN”: self.btn.pos[1] = self.btn.pos[1]-10 The RIGHT and LEFT button press causes the “x” position to be incremented or devremented by 10 pixels. Similarly, TOP and BOTTOM buttons change the “y” value by ±10. Example 1 The complete code is given below − from kivy.app import App from kivy.uix.button import Button from kivy.config import Config from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”400”) Config.set(”graphics”, ”resizable”, ”1”) class MovableButtonApp(App): def movebtn(self,instance): if instance.text ==”RIGHT”: self.btn.pos[0]=self.btn.pos[0]+10 if instance.text == ”LEFT”: self.btn.pos[0] = self.btn.pos[0]-10 if instance.text == ”UP”: self.btn.pos[1] = self.btn.pos[1]+10 if instance.text == ”DOWN”: self.btn.pos[1] = self.btn.pos[1]-10 def build(self): mblo = BoxLayout(orientation=”vertical”) blo = BoxLayout(orientation =”horizontal”) b1 = Button(text=”LEFT”) b1.bind(on_press=self.movebtn) b2 = Button(text = ”RIGHT”) b2.bind(on_press=self.movebtn) b3 = Button(text = ”UP”) b3.bind(on_press=self.movebtn) b4 = Button(text = ”DOWN”) b4.bind(on_press=self.movebtn) blo.add_widget(b1) blo.add_widget(b2) blo.add_widget(b3) blo.add_widget(b4) mblo.add_widget(blo) flo = FloatLayout() self.btn = Button(text=”Movable Button”, size_hint= (.350, .150)) flo.add_widget(self.btn) mblo.add_widget(flo) return mblo MovableButtonApp().run() Output When you run the program, you should see four buttons at the top, and a movable button at the left-bottom corner. Press the buttons and see the movable button changing its position. Here is another example to demonstrate use of button positioning. Let us define a MovableButton class that extends Button class. We define on_touch_down(), on_touch_up() and on_touch_move() methods to process the touch events. The on_touch_down() method checks if the touch event occurred within the button”s bounds, handle the touch event by setting the widget as the current touch target. def on_touch_down(self, touch): if self.collide_point(*touch.pos): touch.grab(self) return True return super().on_touch_down(touch) If the touch event is being handled by our button, update its position by using the on_button_move() method − def on_touch_move(self, touch): if touch.grab_current == self: self.pos = (self.pos[0] + touch.dx, self.pos[1] + touch.dy) Finally, release the button as the current touch target and handle the touch event. def on_touch_up(self, touch): if touch.grab_current == self: touch.ungrab(self) return True return super().on_touch_up(touch) The build() method constructs the window with just a button at the left_bottom position def build(self): return MovableButton(text=”Drag me”, size_hint= (.250, .100)) Example 2 The complete code is given below − from kivy.app import App from kivy.uix.button import Button
Kivy – Logger
Kivy – Logger ”; Previous Next Python”s standard library includes logging module that helps in implementing a robust event logging system in Python applications. The logging mechanism of Kivy builds upon it with certain additional features such as color-coded output on supported terminals, message categorization etc. Each time you run a Kivy application, you get to see a log being displayed in the console window. It appears like this − [INFO ] [Logger ] Record log in C:Usersuser.kivylogskivy_23-07-10_67.txt [INFO ] [deps ] Successfully imported “kivy_deps.gstreamer” 0.3.3 [INFO ] [deps ] Successfully imported “kivy_deps.angle” 0.3.3 [INFO ] [deps ] Successfully imported “kivy_deps.glew” 0.3.1 [INFO ] [deps ] Successfully imported “kivy_deps.sdl2” 0.6.0 [INFO ] [Kivy ] v2.2.0 [INFO ] [Kivy ] Installed at “c:kivyenvLibsitepackageskivy__init__.py” [INFO ] [Python ] v3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] [INFO ] [Python ] Interpreter at “c:kivyenvScriptspython.exe” [INFO ] [Logger ] Purge log fired. Processing… [INFO ] [Logger ] Purge finished! [INFO ] [Factory ] 190 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer ignored) [INFO ] [Window ] Provider: sdl2 [INFO ] [GL ] Using the “OpenGL” graphics system [INFO ] [GL ] GLEW initialization succeeded [INFO ] [GL ] Backend used <glew> [INFO ] [GL ] OpenGL version <b”4.6.0 – Build 31.0.101.3959”> [INFO ] [GL ] OpenGL vendor <b”Intel”> [INFO ] [GL ] OpenGL renderer <b”Intel(R) Iris(R) Xe Graphics”> [INFO ] [GL ] OpenGL parsed version: 4, 6 [INFO ] [GL ] Shading version <b”4.60 – Build 31.0.101.3959”> [INFO ] [GL ] Texture max size <16384> [INFO ] [GL ] Texture max units <32> [INFO ] [Window ] auto add sdl2 input provider [INFO ] [Window ] virtual keyboard not allowed, single mode, not docked [INFO ] [Text ] Provider: sdl2 [INFO ] [Base ] Start application main loop [INFO ] [GL ] NPOT texture support is available These messages tell you which hardware and drivers have been detected and initialized, and which could not be done so. The Logger class in Kivy library provides a singleton instance, and is defined in kivy.logger module. In addition to the logging levels in Python”s logging module (debug, info, warning, error and critical), Kivy has an additional trace level. The Logger object has the methods corresponding to the above logging levels. Each of these methods accept a string argument – message – split in two parts separated by colon ( : ) symbol. The first part is used as a title and the string after colon is the logging message. from kivy.logger import Logger Logger.info(”title: This is a info message.”) Logger.debug(”title: This is a debug message.”) The default logging level is set to info in Kivy”s configuration file. Hence, you get to see such a long logging output. You can set it to any desired logging level by setlevel() method of the Logger object. from kivy.logger import Logger, LOG_LEVELS Logger.setLevel(LOG_LEVELS[“debug”]) Kivy”s logging mechanism is controlled by an environment variable KIVY_LOG_MODE with three possible values: KIVY, PYTHON, MIXED. The default KIVY_LOG_MODE is KIVY, because of which all log messages in the system are output to the Kivy log files and to the console. If you set it to PYTHON mode, no handlers are added, and sys.stderr output is not captured. It is left to the client to add appropriate handlers. In MIXED mode, handlers are added to the Kivy”s Logger object directly, and propagation is turned off. sys.stderr is not redirected. All the logging related configuration parameters are found in the [Kivy] section of the config.ini file. The parameters and their default values are − log_dir = logs log_enable = 1 log_level = info log_name = kivy_%y-%m-%d_%_.txt log_maxfiles = 100 Note that, you can access to the last 100 LogRecords even if the logger is not enabled. from kivy.logger import LoggerHistory print(LoggerHistory.history) Print Page Previous Next Advertisements ”;
Kivy – Discussion
Discuss Kivy ”; Previous Next Kivy is a Python library that helps you to build cross-platform GUI applications for Windows, Linux, iOS as well as Android. Kivy supports touch-enabled input. All the widgets in Kivy GUI framework have the capability to handle multi-touch gestures. Print Page Previous Next Advertisements ”;
Kivy – Calculator App
Kivy – Calculator App ”; Previous Next In this chapter, we shall learn to build a calculator app using the Kivy library. A calculator consists of buttons for each digit and operators. It should have a button with “=” caption that computes the operation, and a button to clear the result. Let us start with the following design in mind − The above layout shows a input box at the top, followed by a 3-column layout for buttons, besides which the four operator buttons are arranged in one column. We shall use a top grid layout with one column, and add the right-aligned TextInput below which we shall put another 2-column grid. The left cell of this grid houses digit, = and C buttons in three columns. The second column is another one-column grid for all the arithmetic operators. The following “kv” file adapts this logic − <calcy>: GridLayout: cols:1 TextInput: id:t1 halign:”right” size_hint:1,.2 font_size:60 GridLayout: cols:2 GridLayout: cols:3 size:root.width, root.height Button: id:one text:”1” on_press:root.onpress(*args) Button: id:two text:”2” on_press:root.onpress(*args) Button: id:thee text:”3” on_press:root.onpress(*args) Button: id:four text:”4” on_press:root.onpress(*args) Button: id:five text:”5” on_press:root.onpress(*args) Button: id:six text:”6” on_press:root.onpress(*args) Button: id:seven text:”7” on_press:root.onpress(*args) Button: id:eight text:”8” on_press:root.onpress(*args) Button: id:nine text:”9” on_press:root.onpress(*args) Button: id:zero text:”0” on_press:root.onpress(*args) Button: id:eq text:”=” on_press:root.onpress(*args) Button: id:clr text:”C” on_press:root.onpress(*args) GridLayout: cols:1 size_hint:(.25, root.height) Button: id:plus text:”+” on_press:root.onpress(*args) Button: id:minus text:”-” on_press:root.onpress(*args) Button: id:mult text:”*” on_press:root.onpress(*args) Button: id:divide text:”/” on_press:root.onpress(*args) Note that each button is bound with onpress() method on its on_press event. The onpress() method basically reads the button caption (its text property) and decides the course of action. If the button has a digit as its caption, it is appended to the text property of the TextInput box. self.ids.t1.text=self.ids.t1.text+instance.text If the button represents any arithmetic operator (+, -, *, /) the number in the textbox at that time is stored in a variable for further operation and the textbox is cleared. if instance.text in “+-*/”: self.first=int(self.ids.t1.text) self.ids.t1.text=”0” self.op=instance.text If the button”s text property is ”=”, the number in the text box at that time is the second operand. Appropriate arithmetic operation is done and the result is displayed in the text box. if instance.text==”=”: if self.first==0: return self.second=int(self.ids.t1.text) if self.op==”+”: result=self.first+self.second if self.op==”-”: result=self.first-self.second if self.op==”*”: result=self.first*self.second if self.op==”/”: result=self.first/self.second self.ids.t1.text=str(result) self.first=self.second=0 Finally, if the button has C as the caption, the text box is set to empty. if instance.text==”C”: self.ids.t1.text=”” self.first=self.second=0 Example The above “kv” file is loaded inside the build() method of the App class. Here is the complete code − from kivy.app import App from kivy.uix.button import Button from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window Window.size = (720,400) class calcy(GridLayout): def __init__(self, **kwargs): super(calcy, self).__init__(**kwargs) self.first=self.second=0 def onpress(self, instance): if instance.text==”C”: self.ids.t1.text=”” self.first=self.second=0 elif instance.text in “+-*/”: self.first=int(self.ids.t1.text) self.ids.t1.text=”0” self.op=instance.text elif instance.text==”=”: if self.first==0: return self.second=int(self.ids.t1.text) if self.op==”+”: result=self.first+self.second if self.op==”-”: result=self.first-self.second if self.op==”*”: result=self.first*self.second if self.op==”/”: result=self.first/self.second self.ids.t1.text=str(result) self.first=self.second=0 else: self.ids.t1.text=self.ids.t1.text+instance.text class calculatorapp(App): def build(self): return calcy(cols=3) calculatorapp().run() Output Run the above program and perform all the basic arithmetic calculations with this app. Print Page Previous Next Advertisements ”;
Kivy – Factory
Kivy – Factory ”; Previous Next The factory class in Kivy is used to automatically register any class or module and instantiate classes from it anywhere in your project. The Factory class is defined in the “kivy.factory” module. Factory Pattern is a software architecture pattern in object-oriented programming. A factory is an object for creating other objects. It is a function or method that returns objects or class from some method call that returns a “new” object may be referred to as a “factory”, as in factory method or factory function. The “kivy.factory.Factory” class creates instances of classes and adds them to the widget tree. The widget tree controls elements on a user interface. Here is an example of creating a custom button class registered with Factory. from kivy.factory import Factory from kivy.uix.button import Button Factory.register(”MyCustomButton”, cls=Button) btn = MyCustomButton( text: “Click me”) Similarly, you can create a class with Factory − from kivy.factory import Factory from kivy.uix.label import Label class MyLabel(Label): pass Factory.register(”MyLabel”, cls=MyLabel) lbl = MyLabel(text: “Hello world”) By default, the first classname you register via the factory is permanent. If you wish to change the registered class, you need to unregister the classname before you re-assign it. from kivy.factory import Factory Factory.register(”NewWidget”, cls=NewWidget) widget = Factory.NewWidget() Factory.unregister(”NewWidget”) Factory.register(”NewWidget”, cls=CustomWidget) customWidget = Factory.NewWidget() Example The following Kivy application uses Factory to register a MyPopup class which is a Popup widget in Kivy library. The Kivy App class code is as follows − from kivy.app import App from kivy.uix.widget import Widget from kivy.lang import Builder from kivy.core.window import Window Window.size = (720,400) Builder.load_file(”popup.kv”) class MyLayout(Widget): pass class FactorydemoApp(App): def build(self): return MyLayout() FactorydemoApp().run() In order to populate the app window, use the following “kv” script (popup.kv) #:import Factory kivy.factory.Factory <MyPopup@Popup> auto_dismiss: False size_hint: 0.6, 0.4 pos_hint: {“x”:0.2, “top”: 0.9} title: “Popup Box” BoxLayout: orientation: “vertical” size: root.width, root.height Label: text: “Hello Kivy” font_size: 24 Button: text: “Close” font_size: 24 on_release: root.dismiss() <MyLayout> BoxLayout: orientation: “vertical” size: root.width, root.height Label: text: “Factory Example” font_size: 32 Button: text: “Click here” font_size: 32 on_release: Factory.MyPopup().open() As you can see, the MyPopup class is registered in the Factory and its open() method is called when the button is clicked Output Run the program to display the window with the “Click here” button. On clicking it, the popup appears on the application window. Print Page Previous Next Advertisements ”;
Kivy – Image Viewer
Kivy – Image Viewer ”; Previous Next In this chapter, we shall build a simple Image Viewer app in Kivy. The code below uses Kivy”s Image widget and buttons for navigation through the list of images in the selected folder. There is also a button which opens a FileChooser to let the user select different folder to view the images in. First, we need to build a list of all the image files in the currently selected folder. We use the os.listdir() method for this purpose. import os self.idx=0 self.fillist=[] dir_path = ”.” for file in os.listdir(dir_path): if file.endswith(”.png”): self.fillist.append(file) The construction of app interface involves a vertical box layout, in which the Image object is placed on top and another horizontal box layout holding three buttons. lo=BoxLayout(orientation=”vertical”) self.img= Image(source=self.fillist[self.idx]) lo.add_widget(self.img) hlo=BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b1 = Button(text = ”Dir”, on_press=self.onButtonPress) self.b2 = Button(text = ”Prev”, on_press=self.previmg) self.b3 = Button(text = ”Next”, on_press=self.nextimg) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) The Image widget displays the first available image to start with. When the button captioned “Next” is clicked, the index pointing to the filelist is incremented; and when the “Previous” button is clicked, it is decremented, loading the indexed image file in the Image object. def previmg(self, instance): self.idx-=1 if self.idx<0: self.idx=0 self.img.source=self.fillist[self.idx] def nextimg(self, instance): self.idx+=1 if self.idx>=len(self.fillist): self.idx=len(self.fillist)-1 self.img.source=self.fillist[self.idx] The third button (captioned Dir) pops up a FileChooser dialog. You can choose the required folder to view. def onButtonPress(self, button): layout=GridLayout(cols=1) fw=FileChooserListView(dirselect=True, filters=[“!*.sys”]) fw.bind(on_selection=self.onselect) closeButton = Button( text = “OK”, size_hint=(None, None), size=(100,75) ) layout.add_widget(fw) layout.add_widget(closeButton) self.popup = Popup( title=”Choose Folder”, content=layout, auto_dismiss=False, size_hint=(None, None), size=(400, 400) ) self.popup.open() Example Images in the current folder populate the fillist to start with. Here is the complete code − from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.popup import Popup from kivy.uix.image import Image from kivy.uix.button import Button from kivy.uix.filechooser import FileChooserListView from kivy.core.window import Window Window.size = (720, 400) class ImageViewerApp(App): def previmg(self, instance): self.idx -= 1 if self.idx < 0: self.idx = 0 self.img.source = self.fillist[self.idx] def nextimg(self, instance): self.idx += 1 if self.idx >= len(self.fillist): self.idx = len(self.fillist) – 1 self.img.source = self.fillist[self.idx] def onButtonPress(self, button): layout = GridLayout(cols=1) fw = FileChooserListView(dirselect=True, filters=[“!*.sys”]) fw.bind(on_selection=self.onselect) closeButton = Button( text=”OK”, size_hint=(None, None), size=(100, 75) ) layout.add_widget(fw) layout.add_widget(closeButton) self.popup = Popup( title=”Choose Folder”, content=layout, auto_dismiss=False, size_hint=(None, None), size=(400, 400) ) self.popup.open() closeButton.bind(on_press=self.on_close) def onselect(self, *args): print(args[1][0]) def on_close(self, event): self.popup.dismiss() def build(self): import os self.idx = 0 self.fillist = [] dir_path = ”.” for file in os.listdir(dir_path): if file.endswith(”.png”): self.fillist.append(file) lo = BoxLayout(orientation=”vertical”) self.img = Image(source=self.fillist[self.idx]) lo.add_widget(self.img) hlo = BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b1 = Button(text=”Dir”, on_press=self.onButtonPress) self.b2 = Button(text=”Prev”, on_press=self.previmg) self.b3 = Button(text=”Next”, on_press=self.nextimg) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) return lo ImageViewerApp().run() Output When you run this code, it will display the image at index “0” − Click the navigation buttons to go forward and back. Click the “Dir” button to select a new folder. Print Page Previous Next Advertisements ”;
Kivy – Buttons
Kivy – Buttons ”; Previous Next A button is one of the most important elements in any GUI library, including Kivy. A button object consists of a label, usually to indicate its purpose (such as one with Start caption, or one with a “folder” icon to indicate “open file action”), and having the ability to respond to certain events such as touch or mouse click. The Button class is defined in the “kivy.uix.button” module. The appearance of a Button object can be configured by the same set of properties that are defined in the Label class. The Button class also inherits from the ButtonBehavior mixin. The Button object is instantiated with the following syntax − b1 = Button(**kwargs) To configure a button, you can specify its properties as keyword arguments to the constructor − background_color − The background color of the button is a ColorProperty in the format (r, g, b, a) with default value [1,1,1,1]. 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. background_down − Background image of the button used as the default graphical representation when the button is pressed. background_normal − Background image of the button used as the default graphical representation when the button is not pressed. In addition to the above, the Button also inherits properties from Label class, some of them as follows − bold − Indicates use of the bold version of your font. It is a BooleanProperty and defaults to False. underline − Adds an underline to the text. This feature requires the SDL2 text provider, it is a BooleanProperty and defaults to False. strikethrough − Adds a strikethrough line to the text. This feature requires the SDL2 text provider. It is a BooleanProperty and defaults to False. text − Text of the label. For example − widget = Button(text=”Hello world”) text is a StringProperty and defaults to ””. color − Text color, in the format (r, g, b, a). It is a ColorProperty ,defaults to [1, 1, 1, 1]. font_size − Font size of the text, in pixels. “font_size” is a NumericProperty and defaults to 15sp. Button class also inherits state property from ButtonBehavior class. state − The state of the button, must be one of ”normal” or ”down”. The state is ”down” only when the button is currently touched/clicked, otherwise its ”normal”. It is an OptionProperty and defaults to ”normal”. Button class also inherits properties such as disabled, height, width and pos, etc., from the Widget class. If you want to display a Button on a Kivy application window, then you can do it by declaring a Button object in build() method, or use the “kv” language script. Displaying a Button Using the build() Method Let us configure the Button with some of the properties explained above − Example from kivy.app import App from kivy.uix.button import Button from kivy.config import Config # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”300”) Config.set(”graphics”, ”resizable”, ”1”) class HelloApp(App): def build(self): b1 = Button(text = “A Kivy Button”, font_size=50, color = [0.8, 0.2, 0.3, 1]) return b1 app = HelloApp() app.run() Output Run this code and you will get the following output − Displaying a Button Using the “kv” Language Method Example Save the following script as “hello.kv”. Button: text: ”A Kivy Button” font_size: ”20pt” underline: True background_color: [1,0,0,1] size_hint: (.25, .25) pos_hint: {”center_x”:.5, ”center_y”:.5} Output Comment out the build() method in the App class and run the application again. You will get the following window as the output − Print Page Previous Next Advertisements ”;
Kivy – Slider
Kivy – Slider ”; Previous Next In the Kivy framework, the Slider widget is an extremely useful control when you want to set value of a continuously variable numeric property. For example, the brightness of TV screen or mobile device or speaker sound. The appearance of the slider widget is a horizontal or vertical bar with a knob sliding over it to set the value. When the knob is to the left of a horizontal slider, it corresponds to a minimum value; and when it is to the extreme right, it corresponds to the maximum. The Slider class is defined in the “kivy.uix.slider” class. from kivy.uix.slider import Slider slider = Slider(**kwargs) To create a basic slider control in Kivy, we can use the following code − from kivy.uix.slider import Slider s = Slider(min=0, max=100, value=25) The default orientation of the slider control is horizontal. Set orientation=”vertical” if needed. You should get a slider as shown below on the Kivy application window. The knob can be moved along the slider with a mouse or touch (in case of a touchscreen). To invoke a certain action on the basis of change in slider value, bind the value property to a certain callback. def on_value_changed(self, instance, val): print (val) s.bind(value = on_value_changed) Here are some of the important properties of the Slider class − max − Maximum value allowed for value. max is a NumericProperty and defaults to 100. min − Minimum value allowed for value. min is a NumericProperty and defaults to 0. orientation − Orientation of the slider. orientation is an OptionProperty and defaults to ”horizontal”. Can take a value of ”vertical” or ”horizontal”. padding − Padding of the slider. The padding is used for graphical representation and interaction. It prevents the cursor from going out of the bounds of the slider bounding box. padding is a NumericProperty and defaults to 16sp. range − Range of the slider in the format (minimum value, maximum value) is a ReferenceListProperty of (min, max) properties. sensitivity − Whether the touch collides with the whole body of the widget or with the slider handle part only. sensitivity is a OptionProperty and defaults to ”all”. Can take a value of ”all” or ”handle”. step − Step size of the slider. Determines the size of each interval or step the slider takes between min and max. step is a NumericProperty and defaults to 0. value − Current value used for the slider. value is a NumericProperty and defaults to 0. value_track − Decides if slider should draw the line indicating the space between min and value properties values. It is a BooleanProperty and defaults to False. value_track_color − Color of the value_line in rgba format. value_track_color is a ColorProperty and defaults to [1, 1, 1, 1]. value_track_width − Width of the track line, defaults to 3dp. Example In the code below, we use three slider widgets to let the user set RGB value for the desired color. The values of the sliders are used to Change the RGB values. For example, the RED slider change sets the value of ”r” component − def on_red(self, instance, val): self.r = int(val)/255 self.colour=[self.r, self.g, self.b, self.t] self.redValue.text = str(int(val)) Similar callbacks for Green and Blue are also coded. These are assigned the value of colur variable which is of ColorProperty type. It is bound to the color property of a Label widget. colour = ColorProperty([1,0,0,1]) def on_colour_change(self, instance, value): self.ttl.color=self.colour As a result, setting RGB values by the sliders changes the text color of the Label. Three slider controls along with the required labels are placed in an inner grid layout with four columns. An upper grid with one column houses a label, whose color is sought to be changed with the slider movement. The complete code is given below − from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.slider import Slider from kivy.uix.label import Label from kivy.properties import ColorProperty, NumericProperty from kivy.core.window import Window Window.size = (720, 400) class SliderExample(App): r = NumericProperty(0) g = NumericProperty(0) b = NumericProperty(0) t = NumericProperty(1) colour = ColorProperty([1, 0, 0, 1]) def on_colour_change(self, instance, value): self.ttl.color = self.colour def on_red(self, instance, val): self.r = int(val) / 255 self.colour = [self.r, self.g, self.b, self.t] self.redValue.text = str(int(val)) def on_green(self, instance, val): self.g = int(val) / 255 self.colour = [self.r, self.g, self.b, self.t] self.greenValue.text = str(int(val)) def on_blue(self, instance, val): self.b = int(val) / 255 self.colour = [self.r, self.g, self.b, self.t] self.blueValue.text = str(int(val)) def build(self): maingrid = GridLayout(cols=1) self.ttl = Label( text=”Slider Example”, color=self.colour, font_size=32 ) maingrid.add_widget(self.ttl) grid = GridLayout(cols=4) self.red = Slider(min=0, max=255) self.green = Slider(min=0, max=255) self.blue = Slider(min=0, max=255) grid.add_widget(Label(text=”RED”)) grid.add_widget(self.red) grid.add_widget(Label(text=”Slider Value”)) self.redValue = Label(text=”0”) grid.add_widget(self.redValue) self.red.bind(value=self.on_red) grid.add_widget(Label(text=”GREEN”)) grid.add_widget(self.green) grid.add_widget(Label(text=”Slider Value”)) self.greenValue = Label(text=”0”) grid.add_widget(self.greenValue) self.green.bind(value=self.on_green) grid.add_widget(Label(text=”BLUE”)) grid.add_widget(self.blue) grid.add_widget(Label(text=”Slider Value”)) self.blueValue = Label(text=”0”) grid.add_widget(self.blueValue) self.blue.bind(value=self.on_blue) self.bind(colour=self.on_colour_change) maingrid.add_widget(grid) return maingrid root = SliderExample() root.run() Output When you run this code, it will produce an output window like the one shown here − Print Page Previous Next Advertisements ”;
Kivy – Vector
Kivy – Vector ”; Previous Next In Euclidean geometry, a vector is an object that represents a physical quantity that has both the magnitude and direction. Kivy library includes Vector class and provides functionality to perform 2D vector operations. The Vector class is defined in kivy.vector module. Kivy”s Vector class inherits Python”s builtin list class. A Vector object is instantiated by passing x and y coordinate values in a cartesian coordinate system. from kivy.vector import Vector v=vector(10,10) The two parameters are accessible either by the subscript operator. First parameter is v[0], and second parameter is v[1]. print (v[0], v[1]) They are also identified as x and y properties of a Vector object. print (v.x, v.y) You can also initialize a vector by passing a two value list or a tuple to the constructor. vals = [10,10] v = Vector(vals) Example The Vector class in Kivy supports vector operations represented by the usual arithmetic operations +, −, / The addition of two vectors (a,b)+(c,d) results in a vector (a+c, b+d). Similarly, “(a,b) – (c,d)” is equal to “(a − c, b − d)”. from kivy.vector import Vector a = (10, 10) b = (87, 34) print (“addition:”,Vector(1, 1) + Vector(9, 5)) print (“Subtraction:”,Vector(9, 5) – Vector(5, 5)) print (“Division:”,Vector(10, 10) / Vector(2., 4.)) print (“division:”,Vector(10, 10) / 5.) Output addition: [10, 6] Subtraction: [4, 0] Division: [5.0, 2.5] division: [2.0, 2.0] Methods in Vector Class Following methods are defined in Kivy”s Vector class − angle() It computes the angle between a vector and an argument vector, and returns the angle in degrees. Mathematically, the angle between vectors is calculated by the formula − $$theta =cos^{-1}left [ frac{xcdot y}{left| xright|left|y right|} right ]$$ The Kivy code to find angle is − Example a=Vector(100, 0) b=(0, 100) print (“angle:”,a.angle(b)) Output angle: -90.0 distance() It returns the distance between two points. The Euclidean distance between two vectors is computed by the formula − $$dleft ( p,q right )=sqrt{left ( q_{1}-p_{1} right )^{2}+left ( q_{2}-p_{2} right )^{2}}$$ The distance() method is easier to use. Example a = Vector(90, 33) b = Vector(76, 34) print (“Distance:”,a.distance(b)) Output Distance: 14.035668847618199 distance2() It returns the distance between two points squared. The squared distance between two vectors x = [ x1, x2 ] and y = [ y1, y2 ] is the sum of squared differences in their coordinates. Example a = (10, 10) b = (5,10) print (“Squared distance:”,Vector(a).distance2(b)) Output Squared distance: 25 dot(a) Computes the dot product of “a” and “b”. The dot product (also called the scalar product) is the magnitude of vector b multiplied by the size of the projection of “a” onto “b”. The size of the projection is $costheta $(where $theta$ is the angle between the 2 vectors). Example print (“dot product:”,Vector(2, 4).dot((2, 2))) Output dot product: 12 length() It returns the length of a vector. length2() method Returns the length of a vector squared. Example pos = (10, 10) print (“length:”,Vector(pos).length()) print (“length2:”,Vector(pos).length2()) Output length: 14.142135623730951 length2: 200 rotate(angle) Rotate the vector with an angle in degrees. Example v = Vector(100, 0) print (“rotate:”,v.rotate(45)) Output rotate: [70.71067811865476, 70.71067811865476] Print Page Previous Next Advertisements ”;