Monday, April 21, 2025

Python Turtle - Window Size, Background Image, Clear Screen

We have multiple options to play around with window sizes. For example, to set width, height, and starting coordinates (x and y) we can use this line:

turtle.setup(800, 500, startx = 0, starty = 0)

Please note, we are talking about window here, not about individual turtle object.

To set background color and window title this source is used:

turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")

After that we have turtle (arrow) object creation, and for loop to create some shapes, so the full source is this one: 

import turtle

turtle.setup(800, 500, startx = 0, starty = 0)
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")

t = turtle.Turtle()

for x in range(4):
    t.left(90)
    t.pensize(5)
    t.fd(50)

    t.pensize(15)
    t.fd(50)

    t.pensize(20)
    t.fd(50)

 


Background Image

It's easy to set background image for turtle window. Just use this line. Make note about .gif image extension:

turtle.bgpic("bg-img.gif")

And this is full working source:

import turtle

turtle.setup(800, 800, startx = 0, starty = 0)
turtle.bgpic("bg-img.gif")
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")

t = turtle.Turtle()

for x in range(4):
    t.left(90)
    t.pensize(5)
    t.fd(50)

    t.pensize(15)
    t.fd(50)

    t.pensize(20)
    t.fd(50)


Pause and Window Clear

We can have pause between operations. In this case, we are using time module and sleep() method to wait for 5 seconds before we cancel whole turtle application. Turtle window is closed with bye() method at the end of operations:

import turtle, time

turtle.setup(800, 800, startx = 0, starty = 0)
turtle.bgpic("bg-img.gif")
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")

t = turtle.Turtle()

for x in range(4):
    t.left(90)
    t.pensize(5)
    t.fd(50)

    t.pensize(15)
    t.fd(50)

    t.pensize(20)
    t.fd(50)

time.sleep(5)
turtle.bye()

To understand more, there's dedicated YouTube tutorial on Turtle Window Size, Background Image and How to Clear Turtle Screen.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...