問題描述
在 Kivy 中,有沒有辦法將圖像對象作為按鈕背景傳遞,而不是圖像文件名?
In Kivy, is there a way to pass image object as a button background, instead of image file name?
button.background_normal
屬性只接受字符串.我想自定義圖像屬性,例如 allow_stretch = False
.
button.background_normal
property accepts only strings. I would like to customize image properties, such as allow_stretch = False
.
如果成功,我如何在按鈕內(nèi)指定圖像對齊方式,例如.讓它左上對齊?
If that succeeds, how can I specify image alignment inside a button, eg. to make it top-left aligned?
推薦答案
source 只是 Button 的一個屬性,正如你所指出的,它是一個字符串.你想要一個 Widget 里面有一個 Widget,這就是 Kivy 工作的基本方式.所以只需按原樣添加圖像.一點定位就可以完成剩下的工作.
The source is just a property of Button and it is a string as you pointed out. You want a Widget inside a Widget, and that is the basic way Kivy works. So just add the Image as it is. A little bit of positioning would do the rest.
你必須小心定位.確保它位于可見部分并且沒有任何東西覆蓋它.我在按鈕后使用標簽,因為它具有透明顏色,因此您可以嘗試使用它.例如,如果您的定位錯誤(嘗試 x:0 y:0
),您可以看到按鈕轉(zhuǎn)到標簽區(qū)域的左下角.
You have to be careful with the positioning. Make sure it is in a visible part and nothing covers it. I use a Label after the button because it has transparent Color so you can experimenting with it. For example if your positioning is wrong (try x:0 y:0
) you can see the button going to the bottom-left corner in the label area.
我使用的圖片是 Kivy 標志:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string("""
<ButtonsApp>:
orientation: "vertical"
Button:
text: "B1"
Image:
source: 'kivy.png'
y: self.parent.y + self.parent.height - 250
x: self.parent.x
size: 250, 250
allow_stretch: True
Label:
text: "A label"
""")
class ButtonsApp(App, BoxLayout):
def build(self):
return self
if __name__ == "__main__":
ButtonsApp().run()
這篇關(guān)于在 Kivy 中將圖像對象作為按鈕背景傳遞的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!