本篇開始:
- 我的開發環境是win11
- python是3.10.7版本
- kivy我設定在2.1.0版本
- 編碼的工具是Visual Studio Code(VS Code)
【本篇說明】上一篇分享了一些 TextInput部件基本用法(可參考:【kivy textinput】TextInput部件基本使用-2),今天接續分享 TextInput的觸發函式。
首先在main.py寫下固定的程式碼
以下.py程式碼:(在vscode開啟python檔案,取名為main.py,以下簡稱.py)from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class firstlayout(BoxLayout):
pass
class Mainapp(App):
def build(self):
return firstlayout()
if __name__ == "__main__":
Mainapp().run()
▲說明:
1.從 kivy.uix.boxlayout這個模組導入 BoxLayout類別 (如果還沒看過,可參考:【kivy layout】BoxLayout類別的使用方法)
2.創建一個class 類別取名為 firstlayout(可自取無限定命名),然後在()填入 BoxLayout,目的是為了繼承 BoxLayout類別所有特性
3.這邊 kivy language(kv),我使用的是"相同命名方式",如果不太懂我說的,可先參考這篇:【kivy language】如何使用 kivy language(kv)

▲說明:main.py程式碼
將屬性及函式寫入 Python檔案
1.以下 main.py程式碼:
from kivy.properties import ObjectProperty
▲說明:導入所需的物件屬性(屬性部分,其他篇章再來介紹)
2.改寫 firstlayout類別內容
class firstlayout(BoxLayout):
a1 = ObjectProperty()
a2 = ObjectProperty()
def btn(self):
self.a1.text = self.a2.text
▲說明:
1.先加入 a1.a2 變數,並使其有物件屬性特性
2.定義函式,取名為 " btn(self) ",可自由命名
3.讓函式本身使 a2.text參數等於 a1.text參數

▲說明:main.py程式碼
在 VSCode新增(kivy)檔案,我取名 main.kv,並且放在同資料夾內

▲說明:我的是放在以下路徑:桌面-> python-> Kivy-> test
寫入 main.kv程式碼
以下.kv程式碼:(在vscode編輯 main.kv,簡稱.kv)
<firstlayout>:
orientation: 'vertical'
a1:b1
a2:b2
Label:
id:b1
text:'Hello! its a label. I can show what you type in textinput.'
font_size: 30
TextInput:
id:b2
font_size: 30 # 文字大小
foreground_color: 0 ,0 ,0 # 文字顏色
background_color: 117/255 ,220/255 ,141/255 #背景顏色
halign: 'right' # 對齊方向
size_hint: 1, 0.3 # 物件寬長大小
cursor_color: 'green' # 游標顏色
cursor_width:5 # 游標寬度
hint_text: 'type some words' # 提示字串
multiline: False
on_text_validate: root.btn()
▲說明:
1.a1:b1,讓 a1等於 b1
2.a2:b2,讓 a2等於 b2
3.id:b1,讓 Label物件的 id參數等於 b1
4.id:b2,讓 TextInput物件的 id參數等於 b2
5.multiline: False,換行取消,這行必須加入,否則按下 enter無法觸發函式
6.on_text_validate: root.btn(),在 TextInput中,按下 enter觸發 mani.py裡面的函式 btn(),也就是將 TextInput輸入內容送到 Label去顯示

▲說明:main.kv程式碼
執行 Python檔案


▲說明:TextInput輸入內容,按下enter鍵,就能在 Label顯示
本篇小結
以上就是 TextInput部件的進階使用方法,如何靈活運用就靠大家的腦力激盪了。
本篇結束:
在自學路上遇到困難是很正常的事,只要堅持到底,相信就會有所成果,期勉大家一同努力。


