Search code examples
pythonturtle-graphicspython-turtle

turtle.Screen().screensize() not outputting the right screensize


I have written some code to place dots all around the screen randomly; however, it does not cover the entire screen:

import turtle
import random

t = turtle.Turtle()

color = ["red", "green", "blue", "pink", "yellow", "purple"]
t.speed(-1)
for i in range(0, 500):
    print(turtle.Screen().screensize())
    z = turtle.Screen().screensize()
    x = z[0]
    y = z[1]
    t.color(color[random.randint(0,5)])
    t.dot(4)
    t.setposition(random.randint(-x,x), random.randint(-y,y))


turtle.done()

output


Solution

  • "Screen" refers to the turtle's logical boundaries (scrollable area) which may not be the same as the window size.

    Call Screen().setup(width, height) to set your window size, then use the Screen().window_width() and Screen().window_height() functions to access its size.

    You could also make sure the screensize matches the window size, then use it as you are doing. Set the screen size with Screen().screensize(width, height).

    Additionally, your random number selection is out of bounds. Use

    random.randint(0, width) - width // 2
    

    to shift the range to be centered on 0.

    Putting it together:

    from random import choice, randint
    from turtle import Screen, Turtle
    
    
    screen = Screen()
    screen.setup(480, 320)
    colors = "red", "green", "blue", "pink", "yellow", "purple",
    t = Turtle()
    t.speed("fastest")
    
    for _ in range(0, 100):
        t.color(choice(colors))
        t.dot(4)
        w = screen.window_width()
        h = screen.window_height()
        t.setposition(randint(0, w) - w // 2, randint(0, h) - h // 2)
    
    screen.exitonclick()