Python Tu中的状态清除

2024-06-16 13:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,要求用户输入一个整数>;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()

Tags: in程序cmdanforinputdeferror
1条回答
网友
1楼 · 发布于 2024-06-16 13:21:57

通常,您不应该计划在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()

绘图完成后,在屏幕上单击以获得一个新的提示,提示输入不同的复杂度因子和新绘图。你知道吗

相关问题 更多 >