KIVY学习笔记——安卓开发上篇完结

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.graphics import Rectangle, Color
class FloatLayoutApp(App):
    def build(self):
        def update_rect(layout, *args):
            """设置背景尺寸,可忽略"""
            layout.rect.pos = layout.pos
            layout.rect.size = layout.size
        float_layout = FloatLayout()
        # 设置背景颜色(可忽略)
        with float_layout.canvas:
            Color(1, 1, 1, 1)
            float_layout.rect = Rectangle(pos=float_layout.pos, size=float_layout.size)
            float_layout.bind(pos=update_rect, size=update_rect)
        # 在布局内的300,200处添加一个为布局0.3,0.2大小的按钮
        button = Button(text='Hello FloatLayout', size_hint=(.3, .2), pos=(300, 200))
        # 将按钮添加到布局内
        float_layout.add_widget(button)
        # 返回布局
        return float_layout
if __name__ == "__main__":
    FloatLayoutApp().run()

#上面是纯python无Kv文件

#main.py
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
class FloatLayoutWidget(FloatLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class FloatLayoutApp(App):
    def build(self):
        return FloatLayoutWidget()
if __name__ == "__main__":
    FloatLayoutApp().run()

#floatlayout.kv
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Rectangle, Color
class BoxLayoutWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 设置背景颜色(可忽略)
        with self.canvas:
            Color(1, 1, 1, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)
            self.bind(pos=self.update_rect, size=self.update_rect)
        # 添加两个按钮
        self.add_widget(Button(text='Hello'))
        self.add_widget(Button(text='BoxLayout'))
    def update_rect(self, *args):
        """设置背景尺寸,可忽略"""
        self.rect.pos = self.pos
        self.rect.size = self.size
class BoxApp(App):
    def build(self):
        return BoxLayoutWidget()
if __name__ == "__main__":
    BoxApp().run()

#上面是纯Python无kv文件

#main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class BoxLayoutWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class BoxApp(App):
    def build(self):
        return BoxLayoutWidget()
if __name__ == "__main__":
    BoxApp().run()

#box.kv
:
    orientation: 'vertical'
    padding:[10, 40, 40, 30]
    canvas:
		Color:
			rgba: [1, 1, 1, 1]
		Rectangle:
			size: self.size
			pos: self.pos
    Button:
        text: 'Hello'
        background_color: .6, .2, .2, 1
    Button:
        text: 'BoxLayout'
        background_color: .2, .6 , .3, 1
    BoxLayout:
        orientation: 'horizontal'
        spacing: 20
        Button:
            text: 'first'
            background_color: .2, .2 , .7, 1
        Button:
            text: 'second'
            size_hint_y: .3
            background_color: .4, .2 , .2, 1
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
from kivy.graphics import Rectangle, Color
class AnchorLayoutWidget(AnchorLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 设置背景颜色(可忽略)
        with self.canvas:
            Color(1, 1, 1, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)
            self.bind(pos=self.update_rect, size=self.update_rect)
        # 嵌套第一个布局
        anchor_first = AnchorLayout(anchor_x='left', anchor_y='top')
        # 添加按钮
        anchor_first.add_widget(Button(text='Hello', size_hint=[.3, .2]))
        # 嵌套第二个布局
        anchor_second = AnchorLayout(anchor_x='right', anchor_y='bottom')
        # 添加按钮
        anchor_second.add_widget(Button(text='Anchor', size_hint=[.3, .2]))
        # 添加到父布局中
        self.add_widget(anchor_first)
        self.add_widget(anchor_second)
    def update_rect(self, *args):
        """设置背景尺寸,可忽略"""
        self.rect.pos = self.pos
        self.rect.size = self.size
class AnchorApp(App):
    def build(self):
        return AnchorLayoutWidget()
if __name__ == "__main__":
    AnchorApp().run()

#上面是纯Python

#main.py
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
class AnchorLayoutWidget(AnchorLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class AnchorApp(App):
    def build(self):
        return AnchorLayoutWidget()
if __name__ == "__main__":
    AnchorApp().run()

#anchor.kv
:
    padding: 20
    AnchorLayout:
        anchor_x: 'left'
        anchor_y: 'top'
        Button:
            text: 'Hello'
            size_hint: .3, .2
    AnchorLayout:
        anchor_x: 'right'
        anchor_y: 'bottom'
        Button:
            text: 'Anchor'
            size_hint: .3, .2
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.graphics import Rectangle, Color
class GridLayoutWidget(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 设置背景颜色(可忽略)
        with self.canvas:
            Color(1, 1, 1, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)
            self.bind(pos=self.update_rect, size=self.update_rect)
        # 指定列数(行数使用rows)
        self.cols = 3
        # 添加按钮
        for i in range(5):
            btn = Button(text=str(i))
            self.add_widget(btn)
    def update_rect(self, *args):
        """设置背尺寸,可忽略"""
        self.rect.pos = self.pos
        self.rect.size = self.size
class GridApp(App):
    def build(self):
        return GridLayoutWidget()
if __name__ == "__main__":
    GridApp().run()

#上面是纯python

#main.py
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
class GridLayoutWidget(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class GridApp(App):
    def build(self):
        return GridLayoutWidget()
if __name__ == "__main__":
    GridApp().run()

#grid.kv
:
    padding: 20
    spacing: 20
    cols: 3
    col_force_default: True
    col_default_width: 120
    row_force_default: True
    row_default_height: 40
    cols_minimum: {0:130, 1:140}
    canvas:
		Color:
			rgba: [1, 1, 1, 1]
		Rectangle:
			size: self.size
			pos: self.pos
    Button:
        text: 'First'
        size_hint_x: None
        width: '100px'
    Button:
        text: 'Second'
    Button:
        text: 'Third'
    Button:
        text: 'Fourth'

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.pagelayout import PageLayout
class PageLayoutWidget(PageLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 创建两个按钮
        bt0 = Button(text='bt0', background_color=[0.3, .9, .3, 1])
        bt1 = Button(text='bt1', background_color=[0.9, .3, .3, 1])
        # 添加到布局中
        self.add_widget(bt0)
        self.add_widget(bt1)
class PageApp(App):
    def build(self):
        return PageLayoutWidget()
if __name__ == "__main__":
    PageApp().run()

#上面是纯python实现

#main.py
from kivy.app import App
from kivy.uix.pagelayout import PageLayout
class PageLayoutWidget(PageLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class PageApp(App):
    def build(self):
        return PageLayoutWidget()
if __name__ == "__main__":
    PageApp().run()

#page.kv
:
    anim_kwargs: {'d': 10, 't': 'linear'}
    page: 2
    border: '100dp'
    swipe_threshold: .8
    Button:
        text: 'Page0'
        background_color: 0.3, .3, .3, 1
    Button:
        text: 'Page1'
        background_color: 0.9, .3, .3, 1
    Button:
        text: 'Page2'
        background_color: 0.3, .9, .3, 1
    Button:
        text: 'Page3'
        background_color: 0.3, .3, .9, 1

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Rectangle, Color
class MyButton(Button):
    """自定义一个按钮,提出公共属性"""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.font_size = 20
        self.size_hint = [0.2, 0.2]
class RelativeLayoutWidget(RelativeLayout):
    pass
class BoxLayoutWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 设置背景颜色(可忽略)
        with self.canvas:
            Color(1, 1, 1, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)
            self.bind(pos=self.update_rect, size=self.update_rect)
        # 创建一个RelativeLayout布局
        relative_layout = RelativeLayoutWidget()
        # 使用自定义按钮
        bt0 = MyButton(text='Bt0', pos_hint={"right":1, "top":1}, background_color=(0.1, 0.5, 0.6, 1))
        bt1 = MyButton(text='Bt1', pos_hint={"x": 0, "top": 1}, background_color=(1, 0, 0, 1))
        bt_relative = MyButton(text='Relative', pos_hint={"center_x":.5, "center_y":.5}, background_color=(0.4, 0.5, 0.6, 1))
        bt2 = MyButton(text='Bt2', pos_hint={"x":0, "y":0}, background_color=(0, 0, 1, 1))
        bt3 = MyButton(text='Bt3', pos_hint={"right":1, "y":0}, background_color=(0.8, 0.9, 0.2, 1))
        # 向RelativeLayout布局内遍历添加元素
        for i in [bt0, bt1, bt_relative, bt2, bt3]:
            relative_layout.add_widget(i)
        # 放一个空的BoxLayout占位
        self.add_widget(BoxLayout())
        # 将RelativeLayout添加到布局中
        self.add_widget(relative_layout)
    def update_rect(self, *args):
        """设置背景尺寸,可忽略"""
        self.rect.pos = self.pos
        self.rect.size = self.size
class RelativeApp(App):
    def build(self):
        return BoxLayoutWidget()
if __name__ == "__main__":
    RelativeApp().run()

#上面是纯python实现

#main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class RelativeLayoutWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class RelativeApp(App):
    def build(self):
        return RelativeLayoutWidget()
if __name__ == "__main__":
    RelativeApp().run()

#relative.kv
from kivy.app import App
from kivy.uix.image import AsyncImage
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scatterlayout import ScatterLayout
from kivy.graphics import Rectangle, Color
class ScatterLayoutWidget(ScatterLayout):
    pass
class BoxLayoutWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 设置背景颜色(可忽略)
        with self.canvas:
            Color(1, 1, 1, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)
            self.bind(pos=self.update_rect, size=self.update_rect)
        # 创建一个ScatterLayout布局
        scatter_layout = ScatterLayoutWidget()
        # 异步加载图片
        image = AsyncImage(source='http://sck.rjkflm.com/images/logo1.png')
        # 将图片添加到ScatterLayout布局中
        scatter_layout.add_widget(image)
        # 将ScatterLayout布局嵌套在BoxLayout布局中
        self.add_widget(scatter_layout)
    def update_rect(self, *args):
        """设置背景尺寸,可忽略"""
        self.rect.pos = self.pos
        self.rect.size = self.size
class ScatterApp(App):
    def build(self):
        return BoxLayoutWidget()
if __name__ == '__main__':
    ScatterApp().run()

#上面是纯Python实现

#main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class ScatterLayoutWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class ScatterApp(App):
    def build(self):
        return ScatterLayoutWidget()
if __name__ == '__main__':
    ScatterApp().run()

#scatter.kv
:
    canvas:
		Color:
			rgba: [1, 1, 1, 1]
		Rectangle:
			size: self.size
			pos: self.pos
	ScatterLayout:
	    Image:
	        source: 'kivy-logo-black-64.png'
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.stacklayout import StackLayout
from kivy.graphics import Rectangle, Color
class StackLayoutWidget(StackLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 设置背景颜色(可忽略)
        with self.canvas:
            Color(1, 1, 1, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)
            self.bind(pos=self.update_rect, size=self.update_rect)
        # 遍历添加按钮
        for i in range(25):
            btn = Button(text=str(i), width=40 + i * 5, size_hint=(None, 0.15))
            self.add_widget(btn)
    def update_rect(self, *args):
        """设置背尺寸,可忽略"""
        self.rect.pos = self.pos
        self.rect.size = self.size
class StackApp(App):
    def build(self):
        return StackLayoutWidget()
if __name__ == '__main__':
    StackApp().run()

#上面是纯Python实现

#main.py
from kivy.app import App
from kivy.uix.stacklayout import StackLayout
class StackLayoutWidget(StackLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
class StackApp(App):
    def build(self):
        return StackLayoutWidget()
if __name__ == '__main__':
    StackApp().run()

#stack.kv
:
    # ['lr-tb', 'tb-lr', 'rl-tb', 'tb-rl', 'lr-bt', 'bt-lr', 'rl-bt', 'bt-rl']
    orientation: 'lr-tb'
    padding: [20, 10]
    spacing: [20, 10]
    canvas:
		Color:
			rgba: [1, 1, 1, 1]
		Rectangle:
			size: self.size
			pos: self.pos
    Button:
        text: 'B0'
        size_hint: [.2, .1]
    Button:
        text: 'B1'
        size_hint: [.2, .1]
    Button:
        text: 'B2'
        size_hint: [.2, .1]
    Button:
        text: 'B3'
        size_hint: [.2, .1]
    Button:
        text: 'B4'
        size_hint: [.2, .1]
    Button:
        text: 'B5'
        size_hint: [.2, .1]
    Button:
        text: 'B6'
        size_hint: [.2, .1]
    Button:
        text: 'B7'
        size_hint: [.2, .1]
    Button:
        text: 'B8'
        size_hint: [.2, .1]
    Button:
        text: 'B9'
        size_hint: [.2, .1]
#main.py
from time import strftime
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
class ClockBoxLayout(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.timing_flag = False
        self.timing_seconds = 0
        self.on_start()
    def on_start(self):
        # 每过0秒执行一次update_time方法
        Clock.schedule_interval(self.update_time, 0)
    def update_time(self, nap):
        if self.timing_flag:
            self.timing_seconds += nap
        # 通过id获取到time_label_id控件,并设置text属性值
        self.ids.time_label_id.text = strftime('[b]%H[/b]:%M:%S')
        m, s = divmod(self.timing_seconds, 60)
        # 同上设置text值
        self.ids.stopwatch.text = ('%02d:%02d.[size=40]%02d[/size]' % (int(m), int(s), int(s * 100 % 100)))
    def start_or_stop(self):
        # 切换状态
        self.ids.start_stop_button_id.text = 'Start' if self.timing_flag else 'Stop'
        self.timing_flag = not self.timing_flag
    def reset_clock(self):
        """重置时钟"""
        if self.timing_flag:
            self.ids.start_stop_button_id.text = 'Start'
            self.timing_flag = False
        self.timing_seconds = 0
class ClockApp(App):
    def build(self):
        return ClockBoxLayout()
if __name__ == '__main__':
    # 设置页面背景
    from kivy.core.window import Window
    Window.clearcolor = [.8, .8, .8, 1]
    ClockApp().run()

#clock.kv
:
    font_size: 25
    bold: True
    border: (2, 2, 2, 2)
:
    orientation: 'vertical'
    Label:
        id: time_label_id
        text: '[b]00[/b]:00:00'
        font_size: 60
        markup: True
    BoxLayout:
        orientation: 'horizontal'
        padding: 20
        spacing: 20
        size_hint: (1, None)
        height: 90
        MyButton:
            id: start_stop_button_id
            text: 'Start'
            on_press: root.start_or_stop()
        MyButton:
            text: 'Reset'
            on_press: root.reset_clock()
    Label:
        id: stopwatch
        text: '00:00.[size=40]00[/size]'
        font_size: 60
        markup: True

 

你可能感兴趣的:(2020年暑假研零笔记)