turtle 定义的函数不立即执行所有代码

turtle defined function not executing all code at once

我正在尝试编写一个程序,允许我使用 turtle 模块绘制一些简单的坐标并使其更加用户友好我想在每次用户按下鼠标左键绘制一个点时显示一个十字.出于某种原因,cross() 函数的最后一位即。在再次按下鼠标左键之前,十字的最后一行不会绘制或出现。我真的很困惑为什么会这样,因为代码肯定正在执行。任何帮助将不胜感激!


wn = t.Screen()
wn.title("graph")
wn.setup(width=600, height=600)
wn.tracer(0)
wn.update()

pen = t.Turtle()
pen.color("black")
pen.shape("classic")
pen.goto(0, 0)
pen.ht()

x = 10
y = 10

def cross(x, y):
    print(x, y)
    pen.pensize(2.5)
    pen.pu()
    pen.goto(x, y)
    pen.pd()
    pen.seth(225)
    pen.color("red")
    pen.fd(50)
    pen.color("black")

    pen.pu()
    pen.goto(x, y)
    pen.pd()
    pen.left(180)
    pen.fd(50)

    pen.pu()
    pen.goto(x, y)
    pen.seth(315)
    pen.pd()
    pen.color("green")
    pen.fd(50)

    pen.pu()
    pen.goto(x, y)
    pen.left(180)
    pen.pd()
    pen.color("yellow")
    pen.fd(50) #for some reason this is not being done
    print("now")

cross(x, y)

while True:
    wn.update()
    wn.onscreenclick(cross)
    wn.mainloop()

此代码表明对 onscreenclick()mainloop() 的基本误解:

while True:
    wn.update()
    wn.onscreenclick(cross)
    wn.mainloop()

让我们重新编写代码以正确使用这些方法,并解决问题:

from turtle import Screen, Pen

def cross(x, y):
    screen.onclick(None)  # disable handler inside handler

    pen.penup()
    pen.goto(x, y)
    pen.pendown()
    pen.setheading(225)
    pen.color('red')
    pen.forward(50)

    pen.penup()
    pen.goto(x, y)
    pen.pendown()
    pen.left(180)
    pen.color('black')
    pen.forward(50)

    pen.penup()
    pen.goto(x, y)
    pen.seth(315)
    pen.pendown()
    pen.color('green')
    pen.forward(50)

    pen.penup()
    pen.goto(x, y)
    pen.left(180)
    pen.pendown()
    pen.color('yellow')
    pen.forward(50)

    screen.update()
    screen.onclick(cross)  # reenable handler on exit

screen = Screen()
screen.title("graph")
screen.setup(width=600, height=600)
screen.tracer(0)

pen = Pen()
pen.hideturtle()
pen.color('black')
pen.pensize(2.5)

x, y = 10, 10

screen.onclick(cross)

cross(x, y)

screen.mainloop()

通常,我会避免使用 tracer()update(),直到您的代码基本可以正常工作为止。从一开始就将它们放入会使您的代码更难调试。