”;
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 −
”;