本篇文章只是个人学习的时候的一些笔记,如果有什么错误的地方还请各位勿喷,手下留情,期待您的指正。
定期会更新文章到www.sea-whales.cn我的个人网站中,有兴趣的小伙伴可以进来看看、
Kivy命名规则
1、类继承App的类名(小写)(除去App)+ .kv
例如:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.graphics import Color,Rectangle
from kivy.properties import ColorProperty, ListProperty
class LoginScreen(GridLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.cols = 2
self.rows = 6
self.add_widget(Label(text='User Name'))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text='password'))
self.password = TextInput(password=True, multiline=False)
self.add_widget(self.password)
self.button = Button(size=(.4, .63), text='iPaoMi', background_color=(0, 0, 1), font_size=15, color=(1, 0, 1))
self.button.bind(on_press=self.on_push)
self.add_widget(self.button)
with self.password.canvas.before:
Color(1, 0.5, 0, 0.5)
self.password = Rectangle(size=self.password.size, pos=self.password.pos)
def on_push(self, inst):
print('inst'+inst.text)
self.button.text = inst.text
self.button.height=12
class MyApp(App):
def build(self):
self.root = root = LoginScreen()
return root
if __name__ == '__main__':
MyApp().run()
创建的kv文件则为 my.kv
代码分离规则:
定义页面:
使用<>:
创建一个页面,页面和py里的类一致。
例如:
且使用缩进标识控件和属性的隶属关系。
<LoginScreen>:
BoxLayout:
Button:
BoxLayout:
Button:
<LoginScreen>:
使用kv文件则无须使用Py文件进行编写布局,可直接如下:
class LoginScreen(App):
pass
Kivy 中文显示
Kivy 属性
位置和尺寸(大小)
尺寸 (大小)
大小有两种写法一种是 size
另一种是 size_hint
size
传入的值是一个固定的宽高值
size_hint
传入的是按照当前窗口比例的宽高值,一般写做如下:
size_hint: .4, .5
或者
size_hint: 0.4, 0.5
位置
位置也有和大小一样的两种属性,一种pos
另一个是pos_hint
pos
pos:
pos_hint
按照宽高比例的写法是允许省略0的写法。
比例值的计算是以左下角为坐标系起点(0,0)
,横向为x轴,纵向为y,假设宽为W,高为L,则窗内任意一点的比例值为[W/x,L/y]
相对于控件, x轴上有三条边可以确定位置:
-
左边界x
-
正中间线center_x
-
右边界right
同样,y轴也有三条可以确定位置:
-
上边界top
-
正中间线center_y
-
下边界y
X轴和Y轴各有三种他们两两组合共有9种写法可以确定一个位置。
pos_hint: {'x': .8, 'y': .4}
或
pos_hint: {'right': .7, 'top': .3}
或者
pos_hint: {'center_y': .7, 'center_x': .3}
以上x、y、right、top、center_y、center_x都是以控件为主,距离布局窗体的X轴和Y轴。