Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

1.

Cài đặt Kivy

 Trước khi cài đặt Kivy cần kiểm tra xem đã cài đặt Python hay chưa
python -m pip install --upgrade pip setuptools virtualenv

 Tạo một môi trường ảo cho các dự án Kivy. Một môi trường ảo sẽ ngăn cách các xung đột có thể
xảy ra khi cài đặt
python -m virtualenv kivy_venv
 Để xử dụng môi trường ảo, ta cần phải kích hoạt nó mỗi lần sử dụng một terminal mới
o Với Windows
kivy_venv\Scripts\activate

C:\Users\asus\kivy_venv\Scripts\activate
o Với Linux
source kivy_venv/bin/activate
 Cài đặt Kivy
python -m pip install kivy[full] kivy_examples

2. Hướng dẫn cơ bản

 Tạo Grid Layout


o Import thư viện cần thiết
from kivy.uix.gridlayout import GridLayout

o Tạo lớp
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super(MyGridLayout, self).__init__(**kwargs)

#tạo grid layout chính


self.cols = 1

#tạo grid layout phụ


self.top_grid = GridLayout()
self.top_grid.cols = 2

#thêm widget
self.top_grid.add_widget(Label(text="Name: "))
#thêm input box
self.name = TextInput(multiline = False)
self.top_grid.add_widget(self.name)

#thêm widget
self.top_grid.add_widget(Label(text="Age: "))
#thêm input box
self.age = TextInput(multiline=False)
self.top_grid.add_widget(self.age)

#thêm grid layout phụ vào app


self.add_widget(self.top_grid)
 Tạo Button
o Import thư viện cần thiết
from kivy.uix.button import Button

o Sử dụng lớp đã tạo


class MyGridLayout(GridLayout):
...
#tạo button
self.submit = Button(text="Submit", font_size = 32)
#gắn button
self.submit.bind(on_press = self.press)
self.add_widget(self.submit)

def press(self, instance):


name = self.name.text
age = self.age.text

#hiện thông tin đã nhập


self.add_widget(Label(text=f"Hello my name is {name} and
i'm {age} years old"))

Hình ảnh chương trình

 Điều chỉnh chiều cao và rộng của các Widget


o Điều chỉnh thông số cho từng Widget

Ta có thể thay đổi thông số của các widget một cách riêng lẻ bằng cách sử dụng đoạn
code dưới đây mỗi khi tạo mới một widget:

Ví dụ:
self.submit = Button(text="Submit",
font_size = 32,
size_hint_y = None,
height = 50,
size_hint_x = None,
width = 200
)

Hình ảnh chương trình

o Điều chỉnh thông số cho cả Layout


Code minh họa:
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super(MyGridLayout, self).__init__(**kwargs)
#tạo grid layout chính
self.cols = 1
self.row_force_default = True
self.row_default_height = 120
self.col_force_default = True
self.col_default_width = 200
#tạo grid layout phụ
self.top_grid = GridLayout(
row_force_default = True,
row_default_height = 80,
col_force_default = True,
col_default_width = 200
)
self.top_grid.cols = 2

Hình ảnh chương trình

 Ngôn ngữ thiết kế Kivy

KV là tệp ngôn ngữ Kivy.

Tệp ngôn ngữ Kivy được sử dụng bởi Kivy, có thể chứa các định nghĩa quy tắc, tiện ích gốc, định
nghĩa lớp động và mẫu.

Một lớp động Kivy cho phép bạn nhanh chóng tạo các widget hoặc quy tắc mới mà không cần
bất kỳ khai báo Python nào. Trước khi không được dùng nữa, các mẫu Kivy đã được sử dụng để
tiết kiệm thời gian của người dùng khi tạo kiểu nội dung, giống như chỉ phải chỉ định giá trị của
nút một lần cho các nút được sử dụng nhiều lần.

Ví dụ:
Trong file My.kv (cùng địa chỉ với file python ban đầu)
<MyGirdLayout>

name:name
age:age

#tạo layout chính


GridLayout:
cols: 1
size: root.width, root.height
#tạo layout phụ
GridLayout:
cols: 2

Label:
text: "Name"
TextInput:
id: name
multiline: False

Label:
text: "Age"
TextInput:
id: age
multiline: False

Button
text: "Submit"
font_size: 32
on_press: root.press()
 Builder trong Kivy
Builder chịu trách nhiệm tạo Parser để phân tích cú pháp tệp kv, hợp nhất kết quả vào các quy
tắc nội bộ, mẫu, v.v.
Theo mặc định, Builder là một phiên bản Kivy chung được sử dụng trong các widget mà bạn có
thể sử dụng để tải các tệp kv khác ngoài các tệp mặc định.
o Import các thư viện cần thiết
from kivy.lang import Builder
o Cú pháp

Builder.load_file('[tên file]')

 Đổi màu widget


o Đổi màu bằng RGB - A
<MyGridLayout>
...

Button
text: "Submit"
font_size: 32
on_press: root.press()
#Đổi màu bằng RGB - A
background_normal: ''
background_color: (1,0,0,1)
o Đổi màu bằng mã hex
#:import utils kivy.utils
<MyGridLayout>
...
Button
text: "Submit"
font_size: 32
on_press: root.press()

#đổi bằng bằng mã hex


background_color: utils.get_color_from_hex('#fa00df')
 Box Layout
o Tạo nút theo chiều dọc
Trong file .kv
<MyLayout>
BoxLayout:
orientation: "horizontal"
size: root.width, root.height

Button
text: "Text 1"

Button
text: "Text 2"

Button
text: "Text 3"

Hình ảnh chương trình

o Tạo nút theo chiều ngang


<MyLayout>
BoxLayout:

orientation: "vertical"

size: root.width, root.height

...

Hình ảnh chương trình

o Thay đổi khoảng cách giữa các nút và khoảng cách giữa nút và lề
<MyLayout>

BoxLayout:

orientation: "vertical"

size: root.width, root.height

padding: 50 #khoảng cách giữa nút và lề

spacing: 20 #khoảng cách giữa các nút

...
Hình ảnh chương trình

o Điều chỉnh button


Nếu muốn điều chỉnh kích cỡ button thay đổi khi kích cỡ khung thay thôi
<MyLayout>

...

Button

text: "Text 3"

size_hint: ([], [])

Nếu muốn cố định kích cỡ của button thì:

<MyLayout>

...

Button

text: "Text 3"

size_hint: (None, None)

width: []

height: []

Nếu muốn để button ở các vị trí khác nhau


<MyLayout>

...

Button

text: "Text 3"

pos_hint: {‘center_x’ :[]}

size_hint: ([], [])

 Đặt thuộc tính cho widget


Trong file .kv
Điều chỉnh thông số chung cho từng widget
<Button>
background_normal: ''
background_color: (0,0,1,1)

<TextInput>
background_color: (150/255,150/255,150/255,1)

<Label>
font_size: 32

<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

padding: 50
spacing: 20

Label:
text: "Ten"
TextInput:
multiline: False

Label:
text: "Tuoi"
TextInput:
multiline: False

Button
text: "Nhap"

Button
text: "Xoa"
#Tuy nhiên ta cũng có thể điều chỉnh thông số cửa các widget riêng lẻ
background_color: (1,0,0,1)
Hình ảnh chương trình

 Thay đổi màu nền và màu chữ của Label

Trong file .kv


...

<MyLayout>

BoxLayout:

orientation: "vertical"

size: root.width, root.height

padding: 50

spacing: 20

Label:

text: "Tên"

font_size: 32

#thay đổi thuộc tính nền

background_color: (1,0,1,1)

canvas.before:
Color:

rgba:self.background_color

Rectangle:

size: self.size

pos: self.pos

#thay đổi thuộc tính chữ

color: (0,1,0,1)

bold: True

italic: True

outline_color: (0,0,0,1)

outline_width: 2

TextInput:

multiline: False

Button

text: "Xóa"

background_color: (1,0,0,1)

Hình ảnh chương trình


 Thay đổi màu nền chương trình
o Cách 1
Trong file .kv
<MyLayout>
canvas.before:
Color:
rgba: (1,1,1,1,)
Rectangle:
size: self.size
pos: self.pos

o Cách 2
Trong file .py
...
from kivy.core.window import Window
...
class MyApp(App):
def build(self):
Window.clearcolor = (1,1,1,1)
return MyLayout()
...

 Sử dụng hình ảnh


Trong file .kv
<MyLayout>
...

Image:
source: 'english-icon.png'
Hình ảnh chương trình

 Float Layout
Trong file .kv
<Button>
font_size: 32
size_hint: (0.3, 0.3)

<MyLayout>
FloatLayout:
size: root.width, root.height

Button
text: "Trái Trên"
# {"x", "y", "trên", "dưới", "trái", "phải"}
pos_hint: {"x": 0, "top": 1}

Button
text: "Phải Trên"
pos_hint: {"x": 0.7, "top": 1}

Button
text: "Giữa"
pos_hint: {"x": 0.35, "y": 0.35}

Button
text: "Trái Dưới"
pos_hint: {"x": 0}
Button
text: "Phải Dưới"
pos_hint: {"x": 0.7, "bottom": 1}
Hình ảnh chương trình

 Cập nhập Label


o Trong file .kv
<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

Label:
id: name_label
text: "Tên bạn là gì?"
font_size: 32

Label:
id: name_label2
text: " "
font_size: 32

TextInput:
id: name_input
multiline: False
size_hint: (1, 0.5)

Button:
size_hint: (1, 0.5)
font_size: 32
text: "Nhập"
on_press: root.press()
o Trong file .py
...

class MyLayout(Widget):
def press(self):

name = self.ids.name_input.text

self.ids.name_label2.text = f'{name}'

self.ids.name_input.text = ''
...

 Tạo Button tròn


Trong file .kv
<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

padding: 50
spacing: 20

Button:
font_size: 32
text: "Vuông"

RoundedButton:
font_size: 32
text: "Tròn"
pos_hint: {'center_x': 0.5}
size_hint: (1, .3)

<RoundedButton@Button>
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba: (48/255, 84/255, 150/255, 1)
RoundedRectangle:
size: self.size
pos: self.pos
radius: [58]

Hình ảnh chương trình

 Accordions trong kivy


Trong file .kv
<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

Accordion:
orientation: "vertical"

AccordionItem:
title:"Panel 1"
Label:
text:"A"
font_size:32

AccordionItem:
title:"Panel 2"
Label:
text:"B"
font_size: 32

AccordionItem:
title:"Panel 3"
Label:
text: "C"
font_size: 32

Hình ảnh chương trình

 Carousels trong kivy

Trong file .kv


<MyLayout>

BoxLayout:

orientation: "vertical"
size: root.width, root.height

Carousel:

direction: "right"

Image:

source: "b1.jpg"

Image:

source: "b2.jpg"

Image:

source: "b3.jpg"
 Tạo checkbox
Trong file .py
...

class MyLayout(Widget):
checks = []
def checkbox_click(self, instance, value, word):
if value == True:
MyLayout.checks.append(word)
words = ''
for i in MyLayout.checks:
words = f'{words} {i}'
self.ids.output_label.text = f"You picked {words}"
else:
MyLayout.checks.remove(word)
words = ''
for i in MyLayout.checks:
words = f'{words} {i}'
self.ids.output_label.text = f"You picked {words}"

...

Trong file .kv


<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

Label:
text: "Pick it"
font_size: 32

GridLayout:
cols: 2

Label:
text: "A"
font_size: 32
CheckBox:
group: "pick_word"
on_active: root.checkbox_click(self, self.active, "A")

Label:
text: "B"
font_size: 32
CheckBox:
group: "pick_word"
on_active: root.checkbox_click(self, self.active, "B")

Label:
id: output_label
text: ""
font_size: 32

Hình ảnh chương trình

 Tạo radio button


Trong file .kv
<MyLayout>
...

Label:
text: "A"
font_size: 32
CheckBox:
group: "pick_word"
on_active: root.checkbox_click(self, self.active, "A")

Label:
text: "B"
font_size: 32
CheckBox:
group: "pick_word"
on_active: root.checkbox_click(self, self.active, "B")
...
Hình ảnh chương trình

 Tạo Popup Box


Trong file .kv
#:import Factory kivy.factory.Factory
<MyPopup@Popup>
auto_dismiss: False
size_hint: 0.6, 0.2
pos_hint: {"x": 0.2, "top": 0.9}

title: "Đây là 1 Popup"

BoxLayout:
orientation: "vertical"
size: root.width, root.height

Label:
text: "1234567890"
font_size: 24
Button:
text: "Ấn để tắt"
font_size: 24
on_release: root.dismiss()

<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

Label:
text: "Popup Box"
font_size: 32

Button:
text: "Popup"
font_size: 32
on_release: Factory.MyPopup().open()
 Đa màn hình với ScreenManager
Trong file .py
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

#định dang màn hình


class Win1(Screen):
pass

class Win2(Screen):
pass

class Win0(ScreenManager):
pass

kv = Builder.load_file('My.kv')

class AppCuaToi(App):
def build(self):
return kv

if __name__ == '__main__':
AppCuaToi().run()

Trong file .kv


Win0:
Win1:

Win2:

<Win1>:
name: "Man1"

BoxLayout:
orientation: "vertical"
size: root.width, root.height

Label:
text: "Màn 1"
font_size: 32

Button:
text: "Go Next"
font_size: 32
on_release:
app.root.current = "Man2"
root.manager.transition.direction = "left"
<Win2>:
name: "Man2"

BoxLayout:
orientation: "vertical"
size: root.width, root.height

Label:
text: "Màn 2"
font_size: 32

Button:
text: "Go Back"
font_size: 32
on_release:
app.root.current = "Man1"
root.manager.transition.direction = "right"

Hình ảnh chương trình

 Tạo Tab với Kivy


Trong file .py
...
from kivy.uix.tabbedpanel import TabbedPanel

Builder.load_file('My.kv')

class MyLayout(TabbedPanel):
pass
...

Trong file .kv


<MyLayout>
do_default_tab: False
TabbedPanelItem:
text: "Tab 1"
Label:
text: "Tesing"

TabbedPanelItem:
text: "Tab 2"
BoxLayout:
Label:
text: "Ấn vào nút"
Button:
text: "Ấn tôi"

TabbedPanelItem:
text: "Tab 3"
Image:
source: "e1.png"

 Sử dụng hình ảnh làm Button


Trong file .py
...

class MyLayout(Widget):
def press_on(self):
self.ids.my_image.source = 'blueb.jpg'

def press_off(self):
self.ids.my_label.text = "Bạn đã ấn nút"
self.ids.my_image.source = 'redb.jpg'

...

Trong file .kv


<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

padding: 50
spacing: 20

Label:
id: my_label
text: "Testing"
font_size: 32

Button:
text: "Nút"
font_size: 32
size_hint: .20, .3
pos_hint: {'center_x': 0.5}
background_color: 0,0,0,0
on_press: root.press_on()
on_release: root.press_off()

Image:
id: my_image
source: "redb.jpg"
center_x: self.parent.center_x
center_y: self.parent.center_y

 Tạo khung tiến trình


Trong file .py
...

class MyLayout(Widget):
def press_it(self):
current = self.ids.my_progress_bar.value

if current == 1:
current = 0
current += 0.25

self.ids.my_progress_bar.value = current
self.ids.my_label.text = f'{int(current*100)}%'

...

Trong file .kv


<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height

Label:
id: my_label
text: "0%"
font_size: 32

ProgressBar:
id: my_progress_bar
value: 0
min: 0
max: 1
pos_hint: {'x': .1}
size_hint_x: .8

Button:
text: "Ấn tôi"
font_size: 32
on_press: root.press_it()

You might also like