Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating pygame.Rect fails when using keyword arguments

Tags:

python

pygame

I have a working program, but if I change my pygame.Rect() constructor / function, then my program crashes.

If you look at the code below, then

button_rect1 = pygame.Rect(450, 300, 100, 100)

works just fine. But if I change it to

button_rect2 = pygame.Rect(left = 450, top = 300, width = 100, height = 100)

then I get the error:

Traceback (most recent call last):
  File "F:\_python_projects\workshift_logger\component_testing.py", line 31, in <module>
    button_rect = pygame.Rect(left = 450, top = 300, width = 100, height = 100)
TypeError: Argument must be rect style object
[Finished in 0.7s with exit code 1]

The only thing I've changed is adding names to the arguments. Why can't I do this, and how can I change my code so I can name my arguments (I want to name them for clarity's sake - in some API's rectangles are (x, y, width, height), in others they are (x1, y1, x2, y2)):

Here's a minimal, standalone example:

##### Imports ######
import pygame


##### Settings #####
window_width  = 1000
window_height =  600


##### Program #####
pygame.init()
window = pygame.display.set_mode((window_width, window_height))

button_rect1 = pygame.Rect(450, 300, 100, 100)                                 # This works
button_rect2 = pygame.Rect(left = 450, top = 300, width = 100, height = 100)   # This doesn't work
like image 567
Einar Avatar asked Jan 18 '26 11:01

Einar


1 Answers

Keyword arguments support for, at least, some was added in 2.0.0 as per the official documentation.

Changed in pygame 2.0.0: Added support for keyword arguments.

So Pygame does support keyword arguments (if the version is >= 2.0.0) .. at least for some.

As per the documentation here, you can instantiate a Rect using three methods:

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

May be, still, there is not a support for the pygame.rect even though there is support for pygame.draw.rect ... in terms of keyword arguments. May be your version is less than 2.0.0

Not sure if I was able to answer the question.

like image 72
Amit Avatar answered Jan 20 '26 03:01

Amit