2025-09-02
Python
00
请注意,本文编写于 183 天前,最后修改于 182 天前,其中某些信息可能已经过时。

目录

Kivy 中文显示
Kivy 属性
位置和尺寸(大小)
尺寸 (大小)
size
size_hint
位置
pos
pos_hint

本篇文章只是个人学习的时候的一些笔记,如果有什么错误的地方还请各位勿喷,手下留情,期待您的指正。 定期会更新文章到www.sea-whales.cn我的个人网站中,有兴趣的小伙伴可以进来看看、

Kivy命名规则

1、类继承App的类名(小写)(除去App)+ .kv 例如:

python
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文件进行编写布局,可直接如下:

python
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轴。

本文作者:sea-whales

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!