Python – 使用 kv 文件更改 kivy 按钮的大小和位置
Kivy 是Python中一个独立于平台的 GUI 工具。因为它可以在Android、IOS、linux和Windows等平台上运行。它基本上是用来开发Android应用程序的,但这并不意味着它不能在桌面应用程序上使用。
在本文中,我们将看到如何在 kv 文件中更改 kivy Python中按钮的大小和位置。
size : This is for static sizing of widgets and takes two arguments i.e. (width, height). Default size of the button = (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.
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
Python3
button = Button(text='Hello world', size_hint=(.6, .6),
pos_hint={'x':.2, 'y':.2})
Python3
## Sample Python application demonstrating the
## How to set button size and position in Kivy using .kv file
###################################################
# import modules
import kivy
# base Class of your App inherits from the App class.
# app:always refers to the instance of your application
from kivy.app import App
# module consist the floatlayout
# to work with FloatLayout first
# you have to import it
from kivy.uix.floatlayout import FloatLayout
# creating the root widget used in .kv file
class FloatLayout(FloatLayout):
pass
# creating the App class in which name
#.kv file is to be named Float_Layout.kv
class BtnApp(App):
# defining build()
def build(self):
# returning the instance of root class
return FloatLayout()
# run the app
if __name__ == "__main__":
BtnApp().run()
Python3
#.kv file implementation of setting position and size of btn
:
Button:
text: "pos_hint "
background_color: 0.1, 0.5, 0.6, 1
# Giving size hint i.e size of button is
# 30 % by height and width of layout .
size_hint: 0.3, 0.3
# positioned at 0 % right and 100 % up / top
# from bottom left, i.e x, top = 0, 100 from bottom left:
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
# Giving size hint i.e size of button is
# 40 % by height and 50 % width of layout .
size_hint: 0.5, 0.4
pos_hint: {"x":.4, "top":1}
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})
Syntax: b1 = Button(size=(100, 100))
Kivy Tutorial – Learn Kivy with Examples.
该方法的 main.py 文件实现 –
Python3
Syntax : b1 = Button(pos=(100, 100))
btn.kv 文件实现的方法——
Python3
button = Button(
text='Hello world',
size_hint=(.5, .25))
输出: