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

2022-01-15 00:00:00 python kivy

问题描述

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

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

kv文件的相关部分是:

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


解决方案

希望这个例子能让你明白:

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

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

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

相关文章