繁体   English   中英

如何使用Kivy创建多个按钮?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM