使用onkey事件时,我的Python龟窗崩溃了

时间:2017-07-20 14:30:37

标签: python turtle-graphics

当我尝试向左移动时,我的Python龟窗崩溃了。我在Python龟图形中使用onkey,当我尝试使用它时,我的窗口完全崩溃。这是我的代码:

import turtle



wn = turtle.Screen()
wn.bgcolor("green")

crosshair = turtle.Turtle()
crosshair.shape("circle")

draw = turtle.Pen()
draw.color("brown")
draw.ht()

while True:

    def left():
        draw.st()
        draw.penup()
        draw.left(90)
        draw.forward(50)
        draw.pendown()
        draw.forward(100)
        draw.left(90)
        draw.forward(50)
        draw.right(90)
        draw.forward(100)
        draw.right(90)
        draw.forward(100)
        draw.right(90)
        draw.forward(100)
        draw.right(90)
        draw.forward(50)

    turtle.listen()
    turtle.onkey(left, "Left")

1 个答案:

答案 0 :(得分:0)

您的代码结构不正确。使用乌龟时,你不应该有一个无限的while True:循环。相反,您应该设置事件处理程序,例如onkey(),并使用mainloop()将控制权交给Tk的事件循环。在Python方面,您不需要在循环内定义left(),将其移动到顶层。这是一个包含上述变化的返工:

from turtle import Turtle, Screen

def left():
    draw.st()

    draw.penup()
    draw.left(90)
    draw.forward(50)
    draw.pendown()

    draw.forward(100)
    draw.left(90)

    draw.forward(50)
    draw.right(90)

    for _ in range(3):
        draw.forward(100)
        draw.right(90)

    draw.forward(50)

    draw.ht()

screen = Screen()
screen.bgcolor("green")

crosshair = Turtle("circle")

draw = Turtle(visible=False)
draw.color("brown")

screen.onkey(left, "Left")
screen.listen()

screen.mainloop()

单击窗口使其激活,然后您可以使用左箭头键调用图形:

enter image description here