2013-09-24 38 views

回答

10

關於問題#2。

Kivy的工作方式是嵌入Widget實例。由於ImageButton是Widget的子類,因此您所要做的就是在Button中嵌入一個Image。注意小部件內的定位是固定的。你必須給出明確的座標。

也就是說,你總是可以嵌入一個Layout來組織你放在按鈕中的東西。

這裏是簡單的前

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的作品嵌入小部件內的小部件。它們是否是標籤,按鈕或佈局並不重要。

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() 
+0

謝謝,tico。然而,圖像相對於父母的位置分配似乎引發了一個問題。假設您的按鈕的文本是動態生成的(即可變長度),並且您希望圖像始終顯示爲文本左側10像素的寬度 - 以確定圖像位置,您是否必須編寫一個函數將按鈕文本中的字符數作爲輸入,並相應地確定x值? –

+0

在這種情況下,您可以在另一個「佈局」內添加一個「標籤」和「圖片」。我會說'BoxLayout'和'orientation:horizo​​ntal'。我想爲你提供另一個例子比較容易。 –