Turtle Graphics Window not responding when the screen.tracer(0) is typed

Viewed 44
from turtle import Screen, Turtle

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

starting_positions = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_positions:
    new_segment = Turtle("square")
    new_segment.penup()
    new_segment.color("white")
    new_segment.goto(position)
    segments.append(new_segment)

game_is_on = True
while game_is_on:
    for seg in segments:
        seg.forward(20)

screen.exitonclick()

When I execute the above code it is giving: output

Please, can someone tell me why is this happening and the solution to this problem?

1 Answers

You have an infinite loop:

game_is_on = True
while game_is_on:
    # do stuff that never changes game_is_on to False or breaks the loop

screen.tracer(0) disables the internal rendering loop that normally manages calls to turtle functions (like seg.forward(20)), turning control of the code over to the turtle client code (that means you!). You're expected to implement some way of periodically deferring control in your thread to the turtle thread so it gets a chance to refresh the GUI and handle interactions.

But when you trigger an infinite loop, that locks the code up indefinitely and the GUI becomes unresponsive.

The typical way to deal with this is turtle.update and turtle.ontimer. update asks turtle to render a frame and ontimer executes a callback after t millseconds.

Here's one way to get things moving again:

import turtle
from turtle import Screen, Turtle

frame_delay_ms = 80
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

starting_positions = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_positions:
    new_segment = Turtle("square")
    new_segment.penup()
    new_segment.color("white")
    new_segment.goto(position)
    segments.append(new_segment)

def tick():
    for seg in segments:
        seg.forward(20)

    turtle.update()
    screen.ontimer(tick, frame_delay_ms)

tick()
screen.exitonclick()
Related