gpt4 book ai didi

python - 如何将对象属性传递给 Kivy .kv 文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:54 25 4
gpt4 key购买 nike

我的问题与 Python/Kivy 有关。我需要根据游戏 block 的类型使用各种纹理(即方形区域,40 x 40)。我尝试了最自然的方式,即将类型定义为对象属性,并测试 .kv 文件中的值。 las,该属性无法识别。我很确定这很简单,是由于我对某些概念的误解造成的。我仍然无法从可用的文档中弄清楚。预先感谢您为我指明了正确的方向。

考虑以下示例代码。这是一个相当大的 block ,但这是它完整运行的成本。

# Imports
from os import system as _system

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.config import Config
from kivy.uix.image import Image

# Size of the map in memory
MAXX = 1001
MAXY = 150

# Size of the display, counted in blocks
MAXSCREENX = 91
MAXSCREENY = 60

# Single block size
BLOCK_SIZE = 40

# Global data structures
game_state = []
mapa = []
player_position = []
equipment = []
eye_direction = 0

# Various subclasees, because of different GIFs defined in the .ky file
class Block(Widget):
typ = NumericProperty(0)

class GameWidget(Widget):
xshift = NumericProperty(0)
yshift = NumericProperty(0)

class ExampleApp(App):
def build(self):
game = GameWidget()
game.xshift = 0
game.yshift = 0
game.screen_map = []
for i in range(MAXSCREENX):
for j in range(MAXSCREENY):
idx = i*MAXSCREENY + j
game.add_widget(Block(), idx)
game.children[idx].pos = (i * BLOCK_SIZE, j * BLOCK_SIZE)
game.children[idx].typ = 2
return game

if __name__ == '__main__':
# Set the window size
Config.set('graphics', 'width', str(MAXSCREENX * BLOCK_SIZE))
Config.set('graphics', 'height', str(MAXSCREENY * BLOCK_SIZE))

ExampleApp().run() # Launch the main application

随附的 example.kv 文件:

#:kivy 1.9.0

<Block>:
size: 40, 40
canvas:
Rectangle:
if self.typ == 2:
source: "Textures/Dirt.png"
pos: self.pos
size: 40, 40

唉,我收到以下错误:

kivy.lang.ParserException: Parser: File "C:\Moje\Example\example.kv", line 7:
...
5: canvas:
6: Rectangle:
>> 7: if self.typ == 2:
8: source: "Textures/Dirt.png"
9: pos: self.pos

最佳答案

您在 kv 语言中不正确地使用了 Python 表达式。查看docs正确的语法。具体来说,您需要将 if 表达式移到 source:

之后
Rectangle:
source: "Textures/Dirt.png" if root.typ == 2
pos: self.pos
size: 40, 40

关于python - 如何将对象属性传递给 Kivy .kv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30820925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com