[英]How to customize style.kv in Kivy
根據Kivy Doc的介紹 ,我可以通過創建將代替標准使用的本地style.kv文件來自定義kivy應用程序外觀。 所以我通過修改按鈕小部件的行為來編輯原始文件,如下所示:
<-Button,-ToggleButton>:
canvas:
Color:
rgba: [1, 0, 0, 1] if self.state == 'normal' else [0, 0, 1, 1]
Rectangle:
pos: self.pos
size: self.size
Color:
rgba: 1, 1, 1, 1
Rectangle:
texture: self.texture
size: self.texture_size
pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)
我希望按鈕的背景變為紅色,並在單擊時變為藍色。 但是什么也沒有發生,並且應用了默認行為。
這是我主文件的內容
from os.path import abspath, dirname, join
from kivy.app import App
from kivy.resources import resource_add_path, resource_find
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class MainLayout(BoxLayout):
def __init__(self, **kwargs):
super(MainLayout, self).__init__(**kwargs)
self.add_widget(Button(text="Button1"))
self.add_widget(Button(text="Button2"))
class MainApp(App):
def build(self):
return MainLayout()
if __name__ == '__main__':
res_path = join(dirname(abspath(__file__)), "custom")
resource_add_path(res_path)
print("find ", resource_find("data/style.kv"))
MainApp().run()
在運行時,style.kv的本地路徑會很好地打印出來。
非常感謝所有幫助!
即使文檔說您可以完全按照自己的方式自定義kivy,但看起來並不可行。 但是,您可以通過使用kivy.lang.Builder
加載修改后的style.kv
kivy.lang.Builder
。 例如:
from kivy.lang import Builder
Builder.load_string('''
<-Button,-ToggleButton>:
canvas:
Color:
rgba: [1, 0, 0, 1] if self.state == 'normal' else [0, 0, 1, 1]
Rectangle:
pos: self.pos
size: self.size
Color:
rgba: 1, 1, 1, 1
Rectangle:
texture: self.texture
size: self.texture_size
pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)
''')
from os.path import abspath, dirname, join
from kivy.app import App
from kivy.resources import resource_add_path, resource_find
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class MainLayout(BoxLayout):
def __init__(self, **kwargs):
super(MainLayout, self).__init__(**kwargs)
self.add_widget(Button(text="Button1"))
self.add_widget(Button(text="Button2"))
class MainApp(App):
def build(self):
return MainLayout()
if __name__ == '__main__':
MainApp().run()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.