[英]My Python turtle window crashes when using onkey event
My Python turtle window crashes when I try to move to the left. 当我尝试向左移动时,我的Python乌龟窗口崩溃。 I am using the onkey in Python turtle graphics and when I try to use it my window completely crashes.
我在Python turtle图形中使用了onkey,当我尝试使用它时,我的窗口完全崩溃了。 Here is my code:
这是我的代码:
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")
Your code isn't structured properly. 您的代码结构不正确。 You should not have an infinite
while True:
loop when using turtle. 在使用
while True:
时,您不应该while True:
循环中设置无限。 Instead, you should set up your event handlers, like onkey()
, and turn control over to Tk's event loop using mainloop()
. 相反,您应该设置事件处理程序,例如
onkey()
,并使用mainloop()
将控制权移交给Tk的事件循环。 Python-wise, you don't need to define left()
inside the loop, move it to the top level. 在Python方面,您无需在循环内定义
left()
只需将其移到顶层即可。 Here's a rework that includes the above changes: 这是包含上述更改的返工:
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()
Click on the window to make it active, then you can use your left arrow key to invoke the graphics: 单击窗口将其激活,然后可以使用向左箭头键调用图形:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.