[Python] Trying to use Python PIL ImageDraw.textbbox because of textsize deprecation but I am...

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have zero issues writing text with textsize but I don't understand what I am doing wrong with textbbox. I am getting error:


    File "c:\Users\email\OneDrive\Personal\Documents\Code\Python\TestPatternGenerator\test.py", line 14, in textwidth, textheight = draw.textbbox("text", font=font) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: ImageDraw.textbbox() missing 1 required positional argument: 'text'
    ​

    from PIL import Image, ImageDraw, ImageFont

    # Create an image object
    img = Image.new("RGB", (400, 400), (255, 255, 255))

    # Create a draw object
    draw = ImageDraw.Draw(img)

    # Define the font to be used for the text
    font = ImageFont.truetype("arial.ttf", 36)

    # Get the text bounding box
    text = "Hello World!"
    textwidth, textheight = draw.textbbox(text, font=font)

    # Calculate the position for the text
    x = (img.width - textwidth) / 2
    y = (img.height - textheight) / 2

    # Draw the text on the image
    draw.text((x, y), text, (0, 0, 0), font=font)

    # Save the image
    img.save("hello_world.png")

    Continue reading...

Compartilhe esta Página