gpt4 book ai didi

python - turtle 按键绑定(bind),为什么老是崩溃?

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:50 31 4
gpt4 key购买 nike

#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)。

但是当我关闭窗口时,会弹出另一个窗口(仅当最后三个是 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

我不太确定在这里要做什么,所有这些错误内容都让我感到困惑,我不明白,我感谢我能得到的所有帮助,谢谢。

最佳答案

问题出在第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() 调用将正确运行窗口。

关于python - turtle 按键绑定(bind),为什么老是崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201574/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com