python - <Python - Kivy> GridLayout 渲染单个 Tile

标签 python kivy kivy-language

我有以下 python 类:

import os

from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image

from crawler.settings import ASSETS_DIR


class Map(GridLayout):
    SIZE = 5

    def __init__(self, **kwargs):
        super(Map, self).__init__(**kwargs)
        for _ in range(0, self.SIZE**2):
            self.add_widget(Tile())


class Tile(Widget):
    def __init__(self, **kwargs):
        super(Tile, self).__init__(**kwargs)
        self.add_widget(Image(source=os.path.join(ASSETS_DIR, 'images/chest.gif')))

以及以下 kv 语言定义:

#:kivy 1.0.9

<Map>:
    size: self.parent.size

<Tile>:
    size: 20, 20

这只会渲染 1 个箱子(实际上循环运行正常,所以也许它们是堆叠在一起的?): enter image description here 如果我更改一些开箱即用的小部件(如按钮)的 Tile 类:

class Map(GridLayout):
SIZE = 5

def __init__(self, **kwargs):
    super(Map, self).__init__(**kwargs)
    for _ in range(0, self.SIZE**2):
        self.add_widget(Button(text=str(_)))

它显示正确的结果: enter image description here

我在 Tile 类中缺少什么才能完成这项工作?我认为这就是问题所在,但到目前为止我找不到它

最佳答案

class Tile(Widget):
    def __init__(self, **kwargs):
        super(Tile, self).__init__(**kwargs)
        self.add_widget(Image(source=os.path.join(ASSETS_DIR, 'images/chest.gif')))

每个 Tile 都是一个包含图像的 Widget,但 Widget 不是布局类,因此图像仅具有默认位置 (0, 0) 和大小(100, 100)

您可以将 Tile 设为 Image,或者将 Widget 替换为 BoxLayout 之类的布局(除非您需要额外的布局行为,否则后一种选择的效率会较低)。

关于python - <Python - Kivy> GridLayout 渲染单个 Tile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38815349/

相关文章:

python - 查找与通配符字符串的所有可能匹配项

python - 使用 PyInstaller --onefile 打包 kivy 时包含 .kv/.json 文件?

python - 如何隐藏/禁用关闭按钮或至少捕获/覆盖内置的 quit() 函数? (基维)

python - 如何在kivy中获取AnchorLayout child 的高度?

python - 即使 Kivy 声音在笔记本电脑上播放正常,也无法在 android 设备上播放

python - pip升级后无法安装numpy

Python ID3 标签、元组和字符串格式问题

python - 如何通过.py文件上的id修改kivy小部件属性

python-3.x - 如何使用kv语言引用kivy中创建的不同屏幕的小部件?

python - Google App Engine (Python) 中的简单 Facebook 连接