Python 海龟州清算

State Clearing in Python Turtle

我正在编写一个程序,要求用户提供一个 > 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()

通常,您不应该计划在 win.exitonclick() 或任何其他将控制权移交给 tkinter 事件循环的海龟命令中存活下来。这样做有一些技巧,但如果避免这种情况更容易,那么不值得麻烦。你想要的是 win.clear() 或者可能是 win.reset()。我在下面合并了它并重写了您的提示逻辑以使用它自己的点击事件,而不是 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()

绘图完成后,单击屏幕以获得不同复杂度的新提示和新绘图。