在kivy中的按钮内组合图像和文本 [英] Combining image and text within a button in kivy
问题描述
在按钮中组合图像/图标和文本的首选方式是什么?例如,您将如何创建一个带有 text = 'my button'
的按钮,以及该文本左侧的图形图标?
What's the preferred way to combine an image/icon and text within a button? For example, how would you create a button with text = 'my button'
, and a graphical icon to the left of that text?
推荐答案
关于问题#2.
Kivy 的工作方式是嵌入 Widget
实例.由于 Image
和 Button
是 Widget 的子类,那么您所要做的就是在 Button 中嵌入一个 Image.请注意,小部件内的定位是固定的.你必须给出明确的坐标.
The way Kivy works is embedding Widget
instances. Since Image
and Button
are subclasses of Widget, then all you have to do is embed an Image inside a the Button. Notice that the positioning inside a widget is fixed. You have to give explicit coordinates.
也就是说,您始终可以嵌入 Layout
来组织您放入 Button 中的内容.
That said, you can always embed a Layout
to organize the stuff you are putting inside the Button.
这是一个简单的例子
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 - 200
x: self.parent.x
Label:
text: "A label"
""")
class ButtonsApp(App, BoxLayout):
def build(self):
return self
if __name__ == "__main__":
ButtonsApp().run()
如何将相对布局嵌入到按钮中的示例
在这种情况下,我使用 StackLayout
来组织 Image
和 Label
内部.正如我所说,Button
是一个 Widget
,Kivy 将小部件嵌入到小部件中.它们是标签、按钮还是布局都没有关系.
In this case I am using a StackLayout
to organize an Image
and a Label
inside. As I said, Button
is a Widget
and Kivy works embedding widgets inside widgets. It doesn't matter if they are labels, buttons or layouts.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string("""
<ButtonsApp>:
orientation: "vertical"
Button:
StackLayout:
pos: self.parent.pos
size: self.parent.size
orientation: 'lr-tb'
Image:
source: 'kivy.png'
size_hint_x: None
width: 74
Label:
size_hint_x: None
width: 100
text: "The text"
Label:
text: "A label"
""")
class ButtonsApp(App, BoxLayout):
def build(self):
return self
if __name__ == "__main__":
ButtonsApp().run()
这篇关于在kivy中的按钮内组合图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!