简体   繁体   中英

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!

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM