#Turtle messing around
import turtle
import os
wn = turtle.Screen()
wn.bgcolor("black")
border = turtle.Turtle()
border.speed(0)
border.penup()
border.color("blue")
border.setposition(-200,-200)
border.setheading(90)
border.pensize(3)
border.pendown()
for x in range(4):
border.fd(400)
border.rt(90)
border.penup()
border.fd(300)
border.rt(90)
border.hideturtle()
#Player graphics
player= turtle.Turtle()
player.setposition(0,-150)
player.color("white")
player.left(90)
player.shape("triangle")
player.shapesize(1)
player.speed(0)
player.penup()
turtle.mainloop()
playerspeed = 15
#Player movement
def moveleft():
x = player.xcor()
x -= playerspeed
if x < -280:
x = -280
player.setx(x)
def moveright():
x = player.xcor()
x += playerspeed
if x > -280:
x = 280
player.setx(x)
wn.listen()
wn.onkeypress(moveleft, "Left")
wn.onkeypress(moveright, "Right")
turtle.mainloop()
我的代码在上面。
每当我运行它时,普通程序就什么都不做(我尝试用wn
替换后三个turtle
)。
但是当我关闭窗口时,又弹出一个窗口(仅当最后三个是乌龟时),并且出现以下错误:
================================
>>>
Traceback (most recent call last):
File "REDACTED", line 54, in <module>
wn.listen()
File "G:\python\lib\turtle.py", line 1438, in listen
self._listen()
File "G:\python\lib\turtle.py", line 710, in _listen
self.cv.focus_force()
File "G:\python\lib\turtle.py", line 426, in focus_force
self._canvas.focus_force()
File "G:\python\lib\tkinter\__init__.py", line 428, in focus_force
self.tk.call('focus', '-force', self._w)
_tkinter.TclError: can't invoke "focus" command: application has been
destroyed
我不太确定该怎么做,所有这些错误的内容都使我感到困惑,我也不明白,我感谢我能获得的所有帮助,谢谢。
答案 0 :(得分:0)
问题出在第34行。当您调用turtle.mainloop()
时,程序将进入无限循环;否则,程序将进入无限循环。下面的代码行都不会执行,包括您的事件监听器。
# ... unchanged code ...
player.speed(0)
player.penup()
turtle.mainloop() # <--- infinite loop! remove this line.
# code below this line is not executed
playerspeed = 15
# ... unchanged code ...
删除此行,您将看到处理程序触发(如果不确定,请添加调试打印)。最后一行的第二个turtle.mainloop()
调用将正确运行窗口。
答案 1 :(得分:0)
让我告诉您您的第一个错误:在第13行,您说for x in range(4):
缩进不适用于此。循环时必须缩进,否则会出现错误。
这是我复制您的代码并删除turtle.mainloop()
时所得到的:
点击链接即可查看
https://i.stack.imgur.com/dI3Lg.gif
此外,turtle.mainloop()
部分除了将其保持在无限循环之外不执行任何操作。
如果绝对要在那里,请将其放在末尾。