如何将纯python中动态创建的按钮添加到以Kivy语言编写的kivy布局中?

时间:2016-01-27 17:30:57

标签: python kivy

我的问题是我需要根据可变数量的网格方块创建一个按钮网格,并将它们放在网格布局上,然后使用屏幕管理器将它们显示在屏幕上。我知道如何使用简单的for循环在纯python中执行此操作,但是我用kivy语言为我的程序编写了布局,并且我不知道如何将按钮添加到网格布局中,因为我没有&#39 ; t知道如何在kv文件中正确引用它们。相关的python代码是:

def buildMap():
    index = 0
    for index in range(0, numberOfGridBlocks):
        mainMap.ids["Map"].add_widget(Button())
        index = index + 1
buildMap() 

kv文件的相关部分是:

ScreenManagement:
    MainMenuScreen:
    NewGameMenuScreen:
    JoinGameMenuScreen:
    TutorialMenuScreen:
    SettingsMenuScreen:
    MapScreen:

<MenuButton>:
    on_press: app.menuButtonPressed()
    size_hint_y: .125
    background_normal: "images/button.png"
    background_down: "images/buttonPressed.png"

<Button>:

<BoxLayout>:
    orientation: "vertical"
<MapLayout>:

<MapScreen>:
    name: "mapScreen"
    MapLayout:
        id: "Map"
        cols: 5

1 个答案:

答案 0 :(得分:3)

我希望这个例子能让你清楚:

test.kv:

#:kivy 1.9.0
ScreenManager:
    MapScreen:

<MapScreen>:
    name: 'map'

    GridLayout:
        id: grid
        cols: 1

main.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.clock import mainthread

NUMBER_OF_BUTTONS = 5


class MapScreen(Screen):

    @mainthread
    def on_enter(self):
        for i in xrange(NUMBER_OF_BUTTONS):
            button = Button(text="B_" + str(i))
            self.ids.grid.add_widget(button)


class Test(App):
    pass


Test().run()

需要@mainthead装饰器稍微延迟功能,因此首先扫描kv文件,使ids列表可行。