首页 > 解决方案 > Python:矩形参数无效

问题描述

嗨,我正在尝试学习 python,但我遇到了这个问题,当我运行我的程序时,它说 rect 参数无效,这是我的代码:

import pygame
pygame.init()

win = pygame.display.set_mode((500,500))

pygame.display.set_caption("First game")

x = 50
y = 50
width = 40
height = 60
vel = 5

run = True
while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    pygame.draw.rect(win, (255, 0, 0),(x, y, width, height, vel))
    pygame.display.update()

pygame.quit()

错误:

Traceback (most recent call last):
 File "...", line 25, in <module>
   pygame.draw.rect(win, (255, 0, 0),(x, y, width, height, vel))
TypeError: Rect argument is invalid

标签: pythonpygameargumentsrectinvalid-argument

解决方案


的第三个参数pygame.draw.rect必须是具有 4 个元素的元组:

pygame.draw.rect(win, (255, 0, 0),(x, y, width, height, vel))

pygame.draw.rect(win, (255, 0, 0),(x, y, width, height))

或者,它也可以是一个pygame.Rect对象:

rect = pygame.Rect(x, y, width, height)
pygame.draw.rect(win, (255, 0, 0), rect)

推荐阅读