在Kivy中将图像对象作为按钮背景传递

时间:2013-06-30 15:59:10

标签: python kivy

在Kivy中,有没有办法将图像对象作为按钮背景传递,而不是图像文件名?

button.background_normal属性只接受字符串。我想自定义图像属性,例如allow_stretch = False

如果成功,我如何在按钮内指定图像对齐,例如。使其左上角对齐?

3 个答案:

答案 0 :(得分:14)

源只是Button的一个属性,它是你指出的一个字符串。你想要一个Widget中的Widget,这是Kivy工作的基本方式。所以只需按原样添加图像即可。剩下的就是做一点定位。

你必须小心定位。确保它在可见部分,没有任何东西覆盖它。我在按钮后面使用Label,因为它具有透明的颜色,因此您可以尝试使用它。例如,如果您的定位错误(尝试x:0 y:0),您可以看到按钮位于标签区域的左下角。

我使用的图片是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()

答案 1 :(得分:7)

除了toto_tico的答案,您还可以在按钮中心找到图像:

Button:
    id: myButton
    Image:
        source: "./buttonImage.PNG"
        center_x: self.parent.center_x
        center_y: self.parent.center_y

答案 2 :(得分:0)

您可以使用

按钮:

  id:mybutton

  background_down: "bgdown.png"

  background_normal: "bg.png"