Python龟程序因“Tkinter回调中的异常”错误而死亡

时间:2017-02-08 19:55:29

标签: python python-3.x turtle-graphics

使用Python:我正在尝试制作一个游戏,其中乌龟不能回溯它的步骤(有点像单人游戏Tron),但是当我尝试运行我的程序时,我得到'Tkinter回调中的异常'。 错误是:

import turtle as t
from turtle import *
setup(1200, 700)
Screen()
title("Turtle Keys")
showturtle()

turns = 0
badpos = []

def k1():

    if t.pos in badpos and badpos.index(t.pos) == turns:
        print("die")
        print(t.pos)
        t.color("red")
        t.bye()
    else:
        pass
    t.forward(10)
    badpos.append(t.pos)

def k2():
    t.left(90)

def k3():
    t.right(90)

t.onkey(k1, "Up")
t.onkey(k2, "Left")
t.onkey(k3, "Right")

listen()
mainloop()

我的计划是:

<test>
- <invoice>
  <id>163-01</id>
  <date>2016-09-06</date>
    - <order>
      <cadreLegal>LAB</cadreLegal>
      <prestataire>907</prestataire>
      <personneProtegee>1951</personneProtegee>
      <dateEtablissement>2016-09-06</dateEtablissement>
      <heureEtablissement>13:22:00</heureEtablissement>
      </order>
 </invoice>
- <invoice>
  <id>163-01</id>
  <date>2016-09-06</date>
    - <order>
      <cadreLegal>LAB</cadreLegal>
      <prestataire>907</prestataire>
      <personneProtegee>1951</personneProtegee>
      <dateEtablissement>2016-09-06</dateEtablissement>
      <heureEtablissement>13:22:00</heureEtablissement>
      </order>
 </invoice>
  </test>
 

1 个答案:

答案 0 :(得分:0)

问题是,在您使用t.forward(10)关闭海龟窗口后,您正在调用t.bye()。下面是我对代码的修改,以解决各种问题,并使其基本完成:

from turtle import Turtle, Screen

def k1():
    turtle.forward(10)

    position = (int(turtle.xcor()), int(turtle.ycor()))

    if position in badpos:
        turtle.color("red")
        screen.bye()

    badpos.add(position)

def k2():
    turtle.left(90)

def k3():
    turtle.right(90)

turtle = Turtle(shape="turtle")

badpos = set()

screen = Screen()
screen.setup(1200, 700)
screen.title("Turtle Keys")

screen.onkey(k1, "Up")
screen.onkey(k2, "Left")
screen.onkey(k3, "Right")

screen.listen()

screen.mainloop()

由于turns变量从未更改其值,因此我删除了turns逻辑,因为它似乎不完整。如果您仍然需要,您需要添加预期的逻辑。