我有一个绘制koch雪花的python脚本。一切正常,除非我在绘图完成前关闭tutle图形窗口,否则我会得到一个很长的错误,最后一行是:tkinter.tc错误:命令名“.38006576”无效。 我觉得就像是java.swing:关闭时退出。这不是默认值。不过,我还没有找到类似Python龟的东西。 有什么建议可以避免这种情况?在
import turtle
import sys
import easygui as eg
def isNum(s):
try:
int(s)
return True
except ValueError:
return False
run = True
while run:
msg = "Input"
title = "Koch snowflake"
fieldNames = ["Length","Depth"]
fieldValues = [] # we start with blanks for the values
fieldValues = eg.multenterbox(msg,title, fieldNames)
a=0
iterations=0
# make sure that none of the fields was left blank
while 1: # do forever, until we find acceptable values and break out
if fieldValues == None:
break
errmsg = ""
# look for errors in the returned values
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg = errmsg + ('"%s" must be filled.\n\n' % fieldNames[i])
elif not (isNum(fieldValues[i].strip())):
errmsg = errmsg + ('"%s" requires a number.\n\n' % fieldNames[i])
if (isNum(fieldValues[1])):
if float(fieldValues[1].strip()) > 13:
errmsg = errmsg + ('Depth cannot be more than 13!')
if errmsg == "":
break # no problems found
else:
# show the box again, with the errmsg as the message
fieldValues = eg.multenterbox(errmsg, title, fieldNames, fieldValues)
#a=float(input("Length: "))
if not fieldValues == None:
if isNum(fieldValues[0]) and isNum(fieldValues[1]):
a=float(fieldValues[0])
iterations=int(fieldValues[1])
else:
sys.exit(0)
#turtle settings
turtle.bgcolor("black")
turtle.reset()
turtle.up()
turtle.setpos(-a*1.5 ,a)
turtle.down()
turtle.delay(0)
turtle.speed(0)
turtle.pencolor("white")
koch_flake = "EJEJE"
for i in range(iterations):
koch_flake = koch_flake.replace("E","EBEJEBE\n")
turtle.down()
for move in koch_flake:
if move == "E":
turtle.forward(a / (3 ** (iterations - 1)))
elif move == "B":
turtle.left(60)
elif move == "J":
turtle.right(120)
turtle.hideturtle()
image = "KochSnowflake.gif"
msg = "Run it again?"
title = "Please Confirm"
if eg.ynbox(msg, title,('Yes', 'No'),image): # show a Continue/Cancel dialog
run = True
else: # user chose Cancel
sys.exit(0)
在一个
Canvas
对象上绘制海龟,从中可以访问Tkinter根。 捕获根的WM_DELETE_WINDOW
事件。当事件被捕获时,del
海龟对象,这样它就不能继续尝试绘图了。控制turtle事件的线程将抛出一个NameError,因为turtle已被删除。捕获NameError异常并忽略它。在这里有这样的代码。我测试了它,它工作正常,不会抛出任何错误:
相关问题 更多 >
编程相关推荐