我正在编写一个程序,要求用户提供一个大于0的整数,该整数用作绘制科赫曲线的复杂度因子。该程序执行一次。再次运行Terminator
时,回溯指向我认为是aTurtle
变量,未清除其最后一个状态。如果我重新启动内核,并清除所有输出,则它可以再次正常运行,然后重复该问题。我在俯视什么?
它是在Jupyter
中构造和执行的,并且也在qtconsole
中进行了测试。代码如下:
import turtle
aTurtle = turtle.Turtle()
#Functions
def drawLS(aTurtle, instructions):
for cmd in instructions:
if cmd == 'F':
aTurtle.forward(5)
elif cmd == '+':
aTurtle.right(70)
elif cmd == '-':
aTurtle.left(70)
else :
print('Error : %s is an unknown command '%cmd)
def applyProduction():
axiom = 'F'
myRules = {'F': 'F-F++F-F'}
for i in range(n):
newString = ""
for ch in axiom :
newString = newString + myRules.get(ch, ch)
axiom = newString
return axiom
def lsystem():
win = turtle.Screen()
aTurtle.up()
aTurtle.setposition(-200, 0)
aTurtle.down()
aTurtle.setheading(0)
newRules = applyProduction()
drawLS (aTurtle, newRules)
win.exitonclick()
#Main
while True:
try:
n = int(input("Enter an integer greater than 0: "))
break
except:
print ("Error, input was not an integer, please try again.")
if n < 1:
print ("Error, input was not an integer greater than 0.")
else:
lsystem()
答案 0 :(得分:0)
通常,您不应该计划保留win.exitonclick()
或将控制权移交给tkinter事件循环的其他任何turtle命令。这样做有很多技巧,但避免这种情况比较容易时,不值得为此而烦恼。您想要的是win.clear()
或可能是win.reset()
。我将其合并到下面,并重写了您的提示逻辑,以使用其自己的click事件而不是exitonclick()
并使用图形numinput()
:
from turtle import Screen, Turtle
def drawLS(turtle, instructions):
for cmd in instructions:
if cmd == 'F':
turtle.forward(5)
elif cmd == '+':
turtle.right(70)
elif cmd == '-':
turtle.left(70)
else:
print('Error : %s is an unknown command '%cmd)
def applyProduction(n):
axiom = 'F'
myRules = {'F': 'F-F++F-F'}
for _ in range(n):
newString = ""
for ch in axiom:
newString += myRules.get(ch, ch)
axiom = newString
return axiom
def lsystem(n):
aTurtle.up()
aTurtle.setposition(-200, 0)
aTurtle.down()
aTurtle.setheading(0)
newRules = applyProduction(n)
drawLS(aTurtle, newRules)
def prompt(x=None, y=None): # dummy arguments for onclick(), ignore them
screen.onclick(None)
n = screen.numinput("Complexity Factor", "Enter an integer greater than 0", minval=1, maxval=100)
if n is not None:
screen.clear()
lsystem(int(n))
screen.onclick(prompt)
screen = Screen()
aTurtle = Turtle()
aTurtle.speed('fastest') # because I have no patience
prompt()
screen.mainloop()
完成绘图后,单击屏幕以获取提示,提示输入不同的复杂度因子和新绘图。