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檔案看到效果了。也可直接到這裡下載案例原始碼學習。