Python – Change kivy button size and position using kv file
Last Updated :
19 Oct, 2021
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
In this article we will see that how can we can change the size and the position of button in kivy python in kv file.
size : This is for static sizing of widgets and takes two arguments i.e. (width, height). Default size of the button = (100, 100).
Syntax: b1 = Button(size=(100, 100))
pos : This is for static placement of widgets and is used to give position to button and by default it is (0, 0) which is the bottom-left corner of the screen.
Syntax : b1 = Button(pos=(100, 100))
size_hint : This is for dynamic sizing of the button and provide hint of size. It contains two arguments i.e. width and height it can be floating values.By default, all widgets have their size_hint=(1, 1).
Python3
button = Button(
text = 'Hello world' ,
size_hint = (. 5 , . 25 ))
|
pos_hint : This is for dynamic placement of the button and provide hint of position. We can define upto 8 keys i.e. it takes arguments in form of dictionary.
pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, “center_x”:1,
“center_y”:1, “top”:1, “bottom”:1(“top”:0)}
Python3
button = Button(text = 'Hello world' , size_hint = (. 6 , . 6 ),
pos_hint = { 'x' :. 2 , 'y' :. 2 })
|
Basic Approach:
1) import kivy
2) import kivyApp
3) import all neaded(like button and layouts to use them)
4) Set minimum version(optional)
5) create Layout class
6) create App class
7) Set up .kv file : Create the buttons and set up the position and size
8) return Layout/widget/Class(according to requirement)
9) Run an instance of the class
Kivy Tutorial – Learn Kivy with Examples.
main.py file implementation of the approach –
Python3
import kivy
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
class FloatLayout(FloatLayout):
pass
class BtnApp(App):
def build( self ):
return FloatLayout()
if __name__ = = "__main__" :
BtnApp().run()
|
btn.kv file implementation of the approach –
Python3
<FloatLayout>:
Button:
text: "pos_hint "
background_color: 0.1 , 0.5 , 0.6 , 1
size_hint: 0.3 , 0.3
pos_hint: { "x" : 0 , "top" : 1 }
Button:
text: "pos"
background_color: 0.4 , 0.5 , 0.6 , 1
size_hint: 0.3 , 0.3
pos: 100 , 100
Button:
text: "size_hint"
background_color: 0 , 0 , 1 , 1
size_hint: 0.5 , 0.4
pos_hint: { "x" :. 4 , "top" : 1 }
|
Output:
Share your thoughts in the comments
Please Login to comment...