Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add buttons that are dynamically created in pure python to a kivy layout that is Written in Kivy Language?

Tags:

python

kivy

My problem is that I need to create a grid of buttons based on a variable number of grid squares, and place them on a grid layout and display them on a screen using the screen manager. I know how to do this in pure python using a simple for loop, but I wrote the layout for my program in kivy language, and I don't know how to add the buttons to the grid layout, because I don't know how to correctly reference them in the kv file. The relevant python code is:

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

The relevant part of the kv file is:

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
like image 392
Steve Hostetler Avatar asked Jan 27 '16 17:01

Steve Hostetler


People also ask

Which among the following class is used for defining layout in Kivy?

PageLayout: Used to create simple multi-page layouts, in a way that allows easy flipping from one page to another using borders.


Video Answer


1 Answers

I hope this example makes it clear for you:

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

The @mainthead decorator is needed to slightly delay the function, so the kv file gets scanned first, making the ids list viable.

like image 58
jligeza Avatar answered Oct 13 '22 08:10

jligeza