【问题标题】:Obscure Pygame Rect error晦涩的 Pygame Rect 错误
【发布时间】:2014-03-18 07:07:41
【问题描述】:

我在这里看到了一些带有错误的主题:“TypeError: Argument must be rect style object”。我无休止地遇到这个错误。

我已阅读文档:

Rect(left, top, width, height) -> Rect
Rect((left, top), (width, height)) -> Rect
Rect(object) -> Rect

我有一种从 pygame.Surface 中提取子表面的方法(它使用表面的原始方法):

def getSubSurface(self, rect):

    """
    Returns the subsurface of a specified rect area in the grict surface.
    """

    return self.surface.subsurface(rect)

问题是当我传递这个矩形时(我已经“取消聚集”了参数以使其更清晰):

sub = []
w = self.tileWidth
h = self.tileHeight
for i in range((self.heightInPixels/self.heightInTiles)):
    y = self.grid.getY(i)
    for j in range((self.widthInPixels/self.widthInTiles)):
        x = self.grid.getX(j)
        sub.append(self.tileset.getSubSurface(pygame.Rect(x,y,w,h)))

我已经明确传递了一个有效的 pygame.Rect,但我什么都没有,我得到:

sub.append(self.tileset.getSubSurface(pygame.Rect(x,y,w,h)))
TypeError: Argument must be rect style object

现在,有趣的部分是:如果我将参数更改为任意 int 值:

sub.append(self.tileset.getSubSurface((1,2,3,4)))

完美运行。 pygame subsurfaces 方法将其作为有效的 Rect。问题是:我所有的实例变量都是有效的整数(即使它们不是,如果我显式转换它们也不起作用)。

没有意义。

为什么它采用显式整数,但不采用我的变量? (如果值的类型不正确,我不会收到“rectstyle”错误,就好像我错误地传递了参数一样)。

【问题讨论】:

  • 创建一个临时的 pygame.Rect 变量,并使用 pdb 检查发生在哪个 x,y,w,h 值。
  • sub.append(self.tileset.getSubSurface(pygame.Rect((x,y,w,h)))) 工作吗?

标签: python pygame rect


【解决方案1】:

如果传递给Rect() 的任何参数不是数值,则会出现此错误。

要查看问题所在,请将以下代码添加到您的方法中:

import numbers
...
sub = []
w = self.tileWidth
h = self.tileHeight
for i in range((self.heightInPixels/self.heightInTiles)):
    y = self.grid.getY(i)
    for j in range((self.widthInPixels/self.widthInTiles)):
        x = self.grid.getX(j)
        # be 100% sure x,y,w and h are really numbers
        assert isinstance(x, numbers.Number)
        assert isinstance(y, numbers.Number)
        assert isinstance(w, numbers.Number)
        assert isinstance(h, numbers.Number)
        sub.append(self.tileset.getSubSurface(pygame.Rect(x,y,w,h)))

【讨论】:

  • 有必要去挖掘一下,发现是“NoneType”的问题。但是开发者没有料到这一点,添加了一个“NoneType in the argument error”(可能是NoneType进入了代码的“else”块,被当成了“rectstyle错误”)。
【解决方案2】:

我找到了问题的根源。我已将变量显式转换为整数:

sub.append(self.tileset.getSubSurface((int(x),int(y),int(w),int(h))))

并且得到了一个“TypeError: int() argument must be a string or a number, not 'NoneType'” 就很清楚了。我的迭代中的“x”和“y”变量最后返回了一个“None”(因为它们从字典中获取它们的值,并且由于它们停止查找键,它们开始返回一个 NoneType)。

我已经解决了修复 getX 和 getY 方法的问题:

def getX(self, pos):

    """
    The getX() method expects a x-key as an argument. It returns its equivalent value in pixels.
    """

    if self.x.get(pos) != None:
        return self.x.get(pos)
    else:
        return 0 # If it is NoneType, it returns an acceptable Rect int value.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多