Исключение в Tkinter Callback (с использованием Python Turtle) - PullRequest
0 голосов
/ 28 сентября 2018

Я делаю текстовую симуляцию лунной посадки в черепахе.Когда игрок нажимает пробел, чтобы перейти к реальному интерфейсу симуляции, все работает отлично.После того, как я нажимаю на экран, чтобы выйти из программы (эта работа еще не завершена, и я на самом деле просто тестирую ее, когда создаю), я получаю эту ошибку:

Exception in Tkinter callback
Traceback (most recent call last):
  File "E:\Python\Python37-32\lib\tkinter\__init__.py", line 1702, in __call__
    return self.func(*args)
  File "E:\Python\Python37-32\lib\turtle.py", line 701, in eventfun
    fun()
  File "E:\Projects\Turtle\Simulations\Lunar Landing Simulation\lunarLandingSim.py", line 54, in start
    playSim()
  File "E:\Projects\Turtle\Simulations\Lunar Landing Simulation\lunarLandingSim.py", line 103, in playSim
    wn.bgcolor("black")
  File "E:\Python\Python37-32\lib\turtle.py", line 1237, in bgcolor
    color = self._colorstr(args)
  File "E:\Python\Python37-32\lib\turtle.py", line 1158, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: black

Вот мой код:

import turtle
import random
import time


delay = 0.1
start = False

##### Use turtle.setheading(0) and turtle.heading() for directional calcualtion

# Lander Variables/Data
vertVel = 0
latVel = 0

fuel = 0

craftMass = 0
fuelMass = 0

craftWeight = craftMass * 0
fuelWeight = fuelMass * 0


# Screen setup
wn = turtle.Screen()
wn.setup(width = 600, height = 600)
wn.title("Lunar Lander")
wn.bgcolor("black")
wn.tracer(0)

# Startup/Intro
greet = turtle.Turtle()
greet.hideturtle()
greet.goto(-235, 250)
greet.color("white")
greet.write("Welcome to Lunar Landing Sim!", font = ("Arial", 25, "normal"))
greet.goto(-175, 175)
greet.write("""The goal is to land on the Lunar surface
below five meters per second.""", font = ("Arial", 15, "normal"))
greet.goto(-175, 0)
greet.write("""Controls:
            Engage engine: Up Key
            Rotate left: Left Key
            Rotate right: Right Key
            Increase throttle: Shift Key
            Decrease throttle: Ctrl key
            """, font = ("Arial", 15, "normal"))
greet.goto(-235, -25)
greet.write("Press the Space Bar to begin.", font = ("Arial", 25, "normal"))


def start():
    wn.clear()
    playSim()

def thrust():
    placeholder = None
    print("Thrust")

def left():
  placeholder = None
  print("Left")

def right():
  placeholder = None
  print("Right")

def shift():
    placeholder = None
    print("Shift")

def ctrl():
    placeholder = None
    print("Control")


wn.onkeypress(start, "space")
wn.onkeypress(thrust, "Up")
wn.onkeypress(left, "Left")
wn.onkeypress(right, "Right")
wn.onkeypress(shift, "Shift_L")
wn.onkeypress(ctrl, "Control_L")
wn.listen()


# Vertical Velocity
vV = turtle.Turtle()
vV.goto(-280, 250)
vV.hideturtle()
vV.color("white")


# Lateral Velocity
lV = turtle.Turtle()
lV.goto(-280, 210)
lV.hideturtle()
lV.color("white")



def playSim():
    while True:
        wn.bgcolor("black")


        # vV = vertical velocity
        vVDisplay = "Vertical velocity: " + str(vertVel)
        vV.write(vVDisplay, font = ("Arial", 25, "normal"))

        # lV = lateral velocity
        lVDisplay = "Lateral velocity: " + str(latVel)
        lV.write(lVDisplay, font = ("Arial", 25, "normal"))

        # Use wn.clear() for clearing the screen at the end of the loop

        wn.exitonclick()

Любая помощь будет высоко ценится.Я не уверен, почему возникает эта ошибка.Кажется, все в порядке.Должно быть, это утомительная вещь, о которой я не знаю.

1 Ответ

0 голосов
/ 28 сентября 2018

Есть несколько проблем с вашим кодом.Наряду с неправильно размещенным exitonclick() у вас есть while True:, которого нет в мире, управляемом событиями, как черепаха.

Но вы также ошиблись ошибкой, которую вы не сделали.Даже если вы правильно разместите exitonclick() и замените while True: событием таймера, нажатие на окно не завершит симуляцию.Вот почему:

exitonclick() в основном вызывает экранный метод onclick() с функцией, которая переносит bye().Но когда вы вызываете clear() на экране в start(), он сбрасывает все настройки onclick() для экрана.Включая набор, установленный exitonclick()!

Ниже приведена моя скелетная переделка вашего кода для решения всех вышеперечисленных проблем:

from turtle import Screen, Turtle

BIG_FONT = ("Arial", 25, "normal")
SMALL_FONT = ("Arial", 15, "normal")

def start():
    screen.clear()
    screen.onclick(lambda x, y: screen.bye())

    vV.write(vVDisplay + str(vertVel), font=BIG_FONT)
    lV.write(lVDisplay + str(latVel), font=BIG_FONT)

    playSim()

def playSim():
    global vertVel, latVel

    screen.bgcolor("black")

    # vV = vertical velocity
    vV.undo()
    vV.write(vVDisplay + str(vertVel), font=BIG_FONT)

    # lV = lateral velocity
    lV.undo()
    lV.write(lVDisplay+ str(latVel), font=BIG_FONT)

    vertVel += 1
    latVel -= 1

    screen.ontimer(playSim, 1000)

# Lander Variables/Data
vertVel = 0
latVel = 0

# Screen setup
screen = Screen()
screen.setup(width=600, height=600)
screen.title("Lunar Lander")
screen.bgcolor("black")

# Startup/Intro
greet = Turtle(visible=False)
greet.color("white")
greet.penup()

greet.goto(-235, 250)
greet.write("Welcome to Lunar Landing Sim!", font=BIG_FONT)

greet.goto(-175, 175)
greet.write("""The goal is to land on the Lunar surface
below five meters per second.""", font=SMALL_FONT)

greet.goto(-175, 0)
greet.write("""Controls:
            Engage engine: Up Key
            Rotate left: Left Key
            Rotate right: Right Key
            Increase throttle: Shift Key
            Decrease throttle: Ctrl key
            """, font=SMALL_FONT)

greet.goto(-235, -25)
greet.write("Press the Space Bar to begin.", font=BIG_FONT)

# Vertical Velocity
vVDisplay = "Vertical velocity: "
vV = Turtle(visible=False)
vV.color("white")
vV.penup()
vV.goto(-280, 250)

# Lateral Velocity
lVDisplay = "Lateral velocity: "
lV = Turtle(visible=False)
lV.color("white")
lV.penup()
lV.goto(-280, 210)

screen.onkeypress(start, "space")

screen.listen()

screen.mainloop()
...