本篇開始:
- 我的開發環境是win11
- python是3.10.7版本
- kivy我設定在2.1.0版本
- 編碼的工具是Visual Studio Code(VS Code)
【本篇說明】在kivy裡面,物件(widget)有很多種,今天要講的Label(或稱為"標籤")是很常用的物件(widget)之一,以下介紹幾個進階的語法。
1.main.py寫下固定的程式碼
以下.py程式碼:(在vscode編輯python檔案,取名為main.py)
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
print(Window.size)
class firstlayout(FloatLayout):
pass
class Mainapp(App):
def build(self):
return firstlayout()
if __name__ == "__main__":
Mainapp().run()

▲說明:main.py程式碼
2.改變text字型
以下.kv程式碼:(在vscode編輯kivy檔案,取名為main.kv,以下簡稱.kv)
Label:
text:'歡迎來到我的 app !'
font_name: './TW-Kai-98_1.ttf'
font_size: 20
bold: True
color: 'white'
size_hint: .3, .3
pos: 300, 0
▲說明:
1.text:這邊我改用中文字體表達
2.font_name:加入欲使用的字體檔案
3.字體檔案須放在.py同一個目錄資料夾


▲說明:須同一個目錄資料夾
3.text_size文字框
如果遇到文字太多,可限制框大小,讓文字內容顯示進去。
以下.kv程式碼:
Label:
text:'Welcome to my app !Welcome to my app !Welcome to my app !'
text_size: 250, 300
font_size: 20
bold: True
color: 'blue'
size_hint: None, None
size: 300, 300
pos_hint:{'x':0.5, 'y':0.5}
▲說明:text_size:讓文字框為250, 300

4.觸發事件:
on_touch_down
on_touch_up
on_touch_move
以上事件,適用於各種物件,不限於Label(標籤)本身,以下展示前兩種語法。
以下.py程式碼
from kivy.properties import NumericProperty, ObjectProperty
▲說明:導入需要的屬性模組(屬性部分,其他篇章再來介紹)
加入以下.py程式碼
class firstlayout(FloatLayout):
touch_down_number = NumericProperty(0)
touch_up_number = NumericProperty(0)
a1 = ObjectProperty()
a2 = ObjectProperty()
def count1(self):
self.touch_down_number += 1
print(self.touch_down_number)
self.a1.text = f'按下的次數:{self.touch_down_number}'
def count2(self):
self.touch_up_number += 1
print(self.touch_up_number)
self.a2.text = f'放開的次數:{self.touch_up_number}'
▲說明:程式碼有關屬性部分,其他篇章再來介紹

以下.kv程式碼:
<firstlayout>:
a1:b1
a2:b2
Label:
text:'歡迎來到我的 app! 按我即可增加數字'
font_name: './TW-Kai-98_1.ttf'
font_size: 40
bold: True
color: 'white'
size_hint: .3, .3
pos_hint: {'center_x': .5, 'y': .7}
on_touch_down: root.count1()
on_touch_up: root.count2()
Label:
id: b1
text:'按下的次數'
font_name: './TW-Kai-98_1.ttf'
font_size: 25
bold: True
color: 'yellow'
size_hint: None, None
size: 200, 200
pos_hint:{'x':0.2}
Label:
id: b2
text:'放開的次數'
font_name: './TW-Kai-98_1.ttf'
font_size: 25
bold: True
color: 'green'
size_hint: None, None
size: 200, 200
pos_hint:{'x':0.6}
▲說明:
1.以上使用三個Label來展示
2.當按下滑鼠時,呼叫main.py檔案中firstlayout類別的函式count1,並記錄按下次數
3.當放開滑鼠時,呼叫main.py檔案中firstlayout類別的函式count2,並記錄放開次數
5.按下執行Python檔案


▲說明:按下(放開)滑鼠時,觸發事件會開始增加次數
6.本篇小結
本篇介紹幾個Label的進階用法,其中觸發事件可適用於各種物件。
本篇結束:
在自學路上遇到困難是很正常的事,只要堅持到底,相信就會有所成果,期勉大家一同努力。