Professional Documents
Culture Documents
hướng dẫn kivy
hướng dẫn 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
o Tạo lớp
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super(MyGridLayout, self).__init__(**kwargs)
#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)
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
)
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
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]')
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()
Button
text: "Text 1"
Button
text: "Text 2"
Button
text: "Text 3"
orientation: "vertical"
...
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"
...
Hình ảnh chương trình
...
Button
<MyLayout>
...
Button
width: []
height: []
...
Button
<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
<MyLayout>
BoxLayout:
orientation: "vertical"
padding: 50
spacing: 20
Label:
text: "Tên"
font_size: 32
background_color: (1,0,1,1)
canvas.before:
Color:
rgba:self.background_color
Rectangle:
size: self.size
pos: self.pos
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)
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()
...
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
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 = ''
...
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]
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
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}"
...
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
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
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
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()
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"
Builder.load_file('My.kv')
class MyLayout(TabbedPanel):
pass
...
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"
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'
...
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
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)}%'
...
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()