[英]How can I create multiple buttons with Kivy?
我正在尋找一種在獼猴桃中創建一行按鈕的方法。 我對kivy很陌生,所以這就是我想出的。
我當前的代碼是:
class StackGameApp(App):
def build(self):
layout = FloatLayout()
b0 = Button(pos_hint={'x': 0, 'center_y': .1}, size_hint=(.1, .1),text= '0')
b1 = Button(pos_hint={'x': .1, 'center_y': .1}, size_hint=(.1, .1),text= '1')
b2 = Button(pos_hint={'x': .2, 'center_y': .1}, size_hint=(.1, .1),text= '2')
b3 = Button(pos_hint={'x': .3, 'center_y': .1}, size_hint=(.1, .1),text= '3')
b4 = Button(pos_hint={'x': .4, 'center_y': .1}, size_hint=(.1, .1),text= '4')
b5 = Button(pos_hint={'x': .5, 'center_y': .1}, size_hint=(.1, .1),text= '5')
b6 = Button(pos_hint={'x': .6, 'center_y': .1}, size_hint=(.1, .1),text= '6')
b7 = Button(pos_hint={'x': .7, 'center_y': .1}, size_hint=(.1, .1),text= '7')
b8 = Button(pos_hint={'x': .8, 'center_y': .1}, size_hint=(.1, .1),text= '8')
b9 = Button(pos_hint={'x': .9, 'center_y': .1}, size_hint=(.1, .1),text= '9')
layout.add_widget(b0)
layout.add_widget(b1)
layout.add_widget(b2)
layout.add_widget(b3)
layout.add_widget(b4)
layout.add_widget(b5)
layout.add_widget(b6)
layout.add_widget(b7)
layout.add_widget(b8)
layout.add_widget(b9)
return layout
它會在屏幕底部返回標記為0-9的一行按鈕。 我將對按鈕進行編碼以返回數字0-9,但這尚未完成。
我幾乎可以肯定,這樣做有更好,更簡單的方法,但我只是不知道它是什么。
絕對應該像jligeza一樣首先學習循環的基礎知識,但從本質上講,您需要按照以下步驟進行操作:
for i in range(0,10):
layout.add_widget(Button(text=str(i))
請注意, for x in 10
注釋,您遇到錯誤是因為錯誤表明整數不可迭代。 相反,如果您使用range(0,10),這是在遍歷以下列表 : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.