Python 在 Kivy 中将图像对象作为按钮背景传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17392202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing image object as a button background in Kivy
提问by blablatros
In Kivy, is there a way to pass image object as a button background, instead of image file name?
在 Kivy 中,有没有办法将图像对象作为按钮背景而不是图像文件名传递?
button.background_normal
property accepts only strings. I would like to customize image properties, such as allow_stretch = False
.
button.background_normal
属性只接受字符串。我想自定义图像属性,例如allow_stretch = False
.
If that succeeds, how can I specify image alignment inside a button, eg. to make it top-left aligned?
如果成功,我如何指定按钮内的图像对齐方式,例如。使其左上对齐?
采纳答案by toto_tico
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.
源只是 Button 的一个属性,正如您指出的那样,它是一个字符串。您需要在 Widget 中包含一个 Widget,这就是 Kivy 工作的基本方式。所以只需按原样添加图像。一点点定位就可以完成剩下的工作。
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.
你必须小心定位。确保它位于可见部分并且没有任何东西覆盖它。我在按钮后使用标签,因为它具有透明的颜色,因此您可以尝试使用它。例如,如果您的定位错误(尝试x:0 y:0
),您可以看到按钮位于标签区域的左下角。
The image I am using is the Kivy logo:
我使用的图像是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()
回答by Guray Yildirim
In addition to toto_tico's answer, you can locate the image at the center of the button as:
除了 toto_tico 的回答之外,您还可以将按钮中心的图像定位为:
Button:
id: myButton
Image:
source: "./buttonImage.PNG"
center_x: self.parent.center_x
center_y: self.parent.center_y
回答by Shivanshu Surya
You can use
您可以使用
Button:
按钮:
id:mybutton
background_down: "bgdown.png"
background_normal: "bg.png"