[英]can't stop loop with user input python turtle
這是我使用 python 龜 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")
當我單擊屏幕時,它應該停止執行代碼。 循環不會停止,也不會說“游戲結束”,我不知道為什么。
我需要幫助。 謝謝!
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
只需刪除參數,然后您將修改正確的變量
def restart(x, y):
go = False
除了@IainShelvington 指出的全局變量問題,我建議您重新設計程序以使用海龜計時器事件:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.