Search code examples
pythonpygamedrawing

How do you get a rectangle drawing to lengthen the more you type in pygame?


In this program when the user types more text I want the rectangle to automatically get longer when the user types to keep the letters inside of the rectangle. However, it doesn't update the rectangle when the text gets longer. How do I fix this?

from pygame import *

init()
screen = display.set_mode((800, 600))

name_font = font.Font(None, 32)
name_text = ''

class Rectangle:


    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.input_rect = Rect(x, y, 140, 32)
        self.text_surface = name_font.render(name_text, True, (255, 255, 255))
        color = Color('lightskyblue3')
        draw.rect(screen, color, self.input_rect, 2)
        self.input_rect.w = self.text_surface.get_width() + 10
        screen.blit(self.text_surface, (self.input_rect.x + 5, self.input_rect.y + 5))

def naming():
    global name_text
    if events.type == KEYDOWN:
        if keys[K_BACKSPACE]:
            name_text = name_text[:-1]
            screen.fill((0, 0, 0))
            rect_1 = Rectangle(200, 200)
        else:
            name_text += events.unicode

while True:
    rect_1 = Rectangle(200, 200)
    for events in event.get():
        keys = key.get_pressed()
        naming()
        if events.type == QUIT:
            quit()
    display.update()
    time.delay(1)

Solution

  • The Rectangle.text_surface is a PyGame Surface. So you can easily get the precise width of the bounding box by simply calling self.text_surface.get_width().

    But you start the size of the border-rect at 140, so this size has to be the maximum of 140 or whatever the new (longer) width is. Another problem is that when the rectangle re-sizes, the old rectangle is left behind. So whenever we now re-draw the rectangle, it erases the background to black.

    demo

    This is all pretty easily encapsulated into the exiting __init__():

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.text_surface = name_font.render(name_text, True, (255, 255, 255))
        rect_width = max( 140, 10 + self.text_surface.get_width() )    # Adjust the width
        color = Color('lightskyblue3')
        self.input_rect = Rect(x, y, rect_width, 32)                   # Use new width (if any)
        draw.rect(screen, (0,0,0) , self.input_rect, 0)                # Erase any existing rect
        draw.rect(screen, color, self.input_rect, 2)
        self.input_rect.w = self.text_surface.get_width() + 10
        screen.blit(self.text_surface, (self.input_rect.x + 5, self.input_rect.y + 5))