kivy提供了Button按鈕一系列屬性來改變樣式,下面列了常用的一些Button屬性並用實操案例進行演練學習。
新建一個main.py,內容代碼如下:
from kivy.app import App from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout class ButtonFloatLayout(FloatLayout): def __init__(self,**kwargs): super(ButtonFloatLayout, self).__init__(**kwargs) bt=Button(text='按鈕', background_color=[1,.5,.5,1],on_release=self.release_button, pos=(300,0),size_hint=(.2,.15)) #添加一個按鈕 bt.bind(on_press=self.press_button) #綁定觸發事件 self.add_widget(bt) #添加到布局 def press_button(self,arg): print('按下按鈕事件已運行') def release_button(self,arg): print('按下並釋放時觸發事件已運行') class ButtonApp(App): def build(self): return ButtonFloatLayout() if __name__ =='__main__': ButtonApp().run()
再建一個button.kv文件,代碼內容如下:
<MyButton@Button>: #自定義按鈕,設置按鈕的公共屬性 size_hint:.2,.15 #設置按鈕大小 <ButtonFloatLayout>: #設置布局背景色,大小 canvas: Color: rgba:[1,1,1,1] Rectangle: pos:self.pos size:self.size Button: #使用原生按鈕 text:'按鈕00' #按鈕顯示文本 bold:10 size_hint:.2,.15 #設置按鈕大小 pos:65,400 #設置x座標=65,y座標=400的位置顯示此按鈕 background_normal:'' #標准背景顏色 background_color:[.1,.5,.5,1] #背景顏色 MyButton: #自定義按鈕 text:'按鈕01' pos:315,400 disabled:True #禁用狀態為真 MyButton: text:'按鈕02' color:[.8,.3,.3,1] #設置按鈕字體顏色 pos:565,400 on_release:root.release_button(self) #觸發事件 on_press: root.press_button(self) #觸發事件,在KV內要觸發多個事件要換行寫 print('laizl.com') MyButton: text:'按鈕03' font_size:15 pos:65,150 MyButton: text:'按鈕04' font_size:25 pos:315,150 state:'normal' #按鈕狀態 MyButton: text:'按鈕05' pos:565,150 state:'down' #按下狀態
建好文件,就可以運行main.py文件看到效果了。也可直接到這里下載案例源碼學習。
因有同學問到我的kivy學習資料里支持中文的方法是怎么解決的,我將解決中文的方法鏈接貼在這里,大家去照着做就可以了,很簡單點擊這個鏈接進入:kivy全局中文支持最簡單的解決方法。