Mikitaka
Mikitaka

Reputation: 49

can't stop loop with user input python turtle

here's my code i'm using the python turtle package:

#setup
import turtle
wn = turtle.Screen()
obj = turtle.Turtle()
go = True


def restart(x, y, go = go):
    go = False
    print(go)
wn.onscreenclick(restart)
wn.listen()

#main loop
while go:
    wn.update()
    obj.forward(0.1)

print("game ended")

when i click the screen it should stop do the code after. the loop won't stop and it won't say "game ended" i am not sure why.

I need help. thanks!

Upvotes: 1

Views: 540

Answers (2)

cdlane
cdlane

Reputation: 41872

Along with your global variable issue, that @IainShelvington points out, I recommend you redesign your program to use turtle timer events:

from turtle import Screen, Turtle

def restart(x, y):
    global running
    running = False

def move():
    if running:
        turtle.forward(0.1)
        screen.ontimer(move)
    else:
        screen.bye()

turtle = Turtle()

screen = Screen()
screen.onscreenclick(restart)

running = True

move()

screen.mainloop()

print("game ended")

Upvotes: 0

Iain Shelvington
Iain Shelvington

Reputation: 32244

You're defining a local variable go in your restart function, when you set it to False you are only changing the local variable's value not the go variable from the outer scope

def restart(x, y, go=go):  # This keyword argument is creating a local variable

Just remove the argument and you will then modify the correct variable

def restart(x, y):
    go = False

Upvotes: 1

Related Questions