在Kivy中将图像对象作为按钮背景传递 [英] Passing image object as a button background in Kivy
问题描述
在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
.
如果成功,如何在按钮内指定图像对齐方式,例如使其左上对齐?
If that succeeds, how can I specify image alignment inside a button, eg. to make it top-left aligned?
推荐答案
源只是Button的一个属性,正如您所指出的,它是一个字符串.您希望在小部件内有一个小部件,这是Kivy工作的基本方式.因此,只需按原样添加Image.一点点定位就可以完成其余的工作.
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
),则可以看到该按钮转到标签区域的左下角.
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徽标:>
The image I am using is the Kivy logo:
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()
这篇关于在Kivy中将图像对象作为按钮背景传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!