如何将以纯python动态创建的按钮添加到以Kivy语言编写的kivy布局中? [英] How do I add buttons that are dynamically created in pure python to a kivy layout that is Written in Kivy Language?

查看:122
本文介绍了如何将以纯python动态创建的按钮添加到以Kivy语言编写的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.

这篇关于如何将以纯python动态创建的按钮添加到以Kivy语言编写的kivy布局中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆