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

标签 python turtle-graphics

#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/

相关文章:

Python/Turtle/Tkinter : in which object or sub-module the list of all symbolic color names can be found?

python : Matplotlib Plotting all data in one plot

python - 不能定义 2 是否为质数

python - 当一只正在移动的 Python turtle 靠近另一只 turtle 时,阻止它

python - 碰撞检测程序在 Turtle 中不起作用

python - 如何在python上画一个时钟?(没有时针或分针,只是一张图)

python - 启动 docker-compose : python modules not installed 时出现问题

python - 任何 Python ORM(SQLAlchemy?)都可以与 Google App Engine 一起使用吗?

python - 在 Python 中使用调试器捕获段错误

python - 在 Python Turtle 图形中制作正方形和旋转正方形的更简单方法