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
PageLayout: Used to create simple multi-page layouts, in a way that allows easy flipping from one page to another using borders.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With