Python TypeError : argument 1 must be pygame. Surface,而不是 pygame.Rect

标签 python python-3.x pygame

我无法理解 Stackoverflow 中的其他问题。当圆圈向屏幕末端移动时,它会向相反的方向移动。

import pygame
import sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])
circle = pygame.draw.circle(screen, [255,0,0],[100,100],30,0)
x = 50
y = 50
x_speed = 5
y_speed = 5

done = "False"
while done == "False":
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done="True"
    pygame.time.delay(20)
    pygame.draw.rect(screen,[255,255,255],[x,y,30,30],0)
    x = x + x_speed
    y = y + y_speed
    if x > screen.get_width() - 30 or x < 0:
        x_speed = -x_speed
    if y > screen.get_height() - 30 or y < 0:
        y_speed = -y_speed
    screen.blit(circle,[x,y])
    pygame.display.flip()

pygame.quit()

发出错误消息但未执行。

screen.blit(circle,[x,y])
TypeError: argument 1 must be pygame.Surface, not pygame.Rect

有什么问题吗?

最佳答案

pygame.draw.circle返回 pygame.Rect不是pygame.Surface并且你只能blit 表面而不是矩形(这就是回溯告诉你的)。因此,创建一个表面对象,使用 pygame.draw.circle 在其上绘制一个圆圈,然后在主循环中将该表面传输到屏幕上。

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])

# A transparent surface with per-pixel alpha.
circle = pygame.Surface((60, 60), pygame.SRCALPHA)
# Draw a circle onto the `circle` surface.
pygame.draw.circle(circle, [255,0,0], [30, 30], 30)

x = 50
y = 50
x_speed = 5
y_speed = 5

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    pygame.time.delay(20)
    screen.fill((40, 40, 40))
    x = x + x_speed
    y = y + y_speed
    if x > screen.get_width() - 60 or x < 0:
        x_speed = -x_speed
    if y > screen.get_height() - 60 or y < 0:
        y_speed = -y_speed
    # Now blit the surface.
    screen.blit(circle, [x, y]) 
    pygame.display.flip()

pygame.quit()
sys.exit()

关于Python TypeError : argument 1 must be pygame. Surface,而不是 pygame.Rect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44471789/

相关文章:

python - 在 Python 中一次读取标准输入行

python - 使用 tf.where() 通过 2d 条件选择 3d 张量并用键和值替换 2d 索引中的元素

python - 如何在python中将特定整数转换为日期时间

python - 如何用 Python joblib 填充全局变量?

Python 邻居都指向相同的值

python - 为什么我们需要在 surface.blit() 之后进行 display.update() 操作?

python - 读取文件时出现 UnicodeEncodeError

python - 我应该如何处理与 getter/setter 相关的 Python 列表属性?

python-3.x - 在这种情况下使用 TKinter 捕获 key

python - 无法在 pygame 中改变颜色?