The argument width of pygame.draw.rect() fills a rect problem

Question:

I’m struggling with pygame.draw.rect(). My goal is to make outline(border line) of a rectangle appear.

Issue

I put a text:

  • text_surf = test_font.render('Rect Test', False, 'black')
  • screen.blit(text_surf, text_rect)

I put a pink rectangle under the text:

  • text_rect = text_surf.get_rect(center=(400, 100))
  • pygame.draw.rect(screen, 'pink', text_rect)

Last, put another rectangle under the previous one, and used width argument to make green outline:

  • pygame.draw.rect(screen, 'green', text_rect, 50)

I ran my code. I only saw a text and a green rectangle (not green outline)

What I tried

  • I wrote an argument name width to specify what the int is for.
    • pygame.draw.rect(screen, 'green', text_rect, width=50) -> didn’t work
  • I changed the order of code for the rectangles. -> didn’t work
    • I could only saw a text and a pink rectangle
pygame.draw.rect(screen, 'pink', text_rect)
pygame.draw.rect(screen, 'green', text_rect, 50)
screen.blit(text_surf, text_rect)

# Change order -> didn't work!
pygame.draw.rect(screen, 'green', text_rect, 50)
pygame.draw.rect(screen, 'pink', text_rect)
screen.blit(text_surf, text_rect)

How can I make outline appear?

My code

from cgitb import text
import pygame
from sys import exit

pygame.init()

screen = pygame.display.set_mode((800, 400))
pygame.display.set_caption('Rect Test')
clock = pygame.time.Clock()
test_font = pygame.font.Font(None, 50)

# Text and rectangle
text_surf = test_font.render('Rect Test', False, 'black')
text_rect = text_surf.get_rect(center=(400, 100))


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    pygame.draw.rect(screen, 'pink', text_rect)

    # I want to make a border line but it fills the rectangle
    pygame.draw.rect(screen, 'green', text_rect, 50)
    screen.blit(text_surf, text_rect)

    pygame.display.update()
    clock.tick(60)

What I want
What I want

What I got
What I got

Asked By: Miu

||

Answers:

You have specified the width of the border rect to be fifty pixels. From your desired image, it seems like that is not correct.

It also seems like you want the border to be larger than the text rect, there’s a neat method that helps you resize rects:

border_rect = text_rect.inflate(5,5)

Then you draw the border with a width of five:

pygame.draw.rect(screen, 'green', border_rect, width=5)

This will show:

Bordered text

Answered By: import random
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.