[英]Python Turtle for loop running infinitely
I have some Turtle code that I've successfully run before to draw the Sierpinski Gasket in Repl.it's Python with Turtle IDE, but recently when I've tried to run it again, it successfully does everything except once it hits the for loop, the turtle just starts spinning and doesn't execute the lines in the for loop until much later. 我有一些Turtle代码已经成功运行过,然后才能在Repl.it的Python中使用Turtle IDE绘制Sierpinski密封垫,但是最近当我再次尝试运行它时,它成功完成了所有工作,除非遇到了for循环,乌龟只是开始旋转,直到很久以后才执行for循环中的行。
I've added a print(i) into the forloop and it is printing 0 repeatedly as if it were an infinite loop 我已将print(i)添加到forloop中,并且它反复打印0就像是一个无限循环
import turtle
from turtle import *
t = Turtle()
t.speed(0)
t.shape('turtle')
t.color('dark green')
def SGRules(char):
if char == 'F':
return 'F+F-F-F+F'
else:
return char
def processStr(oldstr, Fractal_Rules):
newstr = ""
for char in oldstr:
newstr = newstr + Fractal_Rules(char)
return newstr
def createLSystem(iteration, axiom, Fractal_Rules):
startstr = axiom
endstr = ""
for i in range(iteration):
endstr = processStr(startstr, Fractal_Rules)
startstr = endstr
return endstr
def drawLSystem(aturtle, lsys, angle, length):
for cmd in lsys:
if cmd == 'F':
aturtle.forward(length)
elif cmd == '+':
aturtle.left(angle)
elif cmd == '-':
aturtle.right(angle)
sgstr = createLSystem(4, 'F', SGRules)
print(sgstr)
drawLSystem(t, sgstr, 120, 20)
for i in range(2):
print(i)
t.left(120)
t.forward(20 * 2**4)
It should just draw the 2 sides of the outer triangle remaining as soon as it reaches the bottom right corner. 一旦到达右下角,它应该只绘制剩余的外部三角形的2个边。
This cleanup of your code runs fine for me on repl.it and in the Python console: 您的代码清理对我而言在repl.it和Python控制台中运行良好:
from turtle import Screen, Turtle
ANGLE = 120
LENGTH = 20
ITERATIONS = 4
def SGRules(character):
if character == 'F':
return 'F+F-F-F+F'
return character
def processStr(string, rules):
new_string = ""
for character in string:
new_string += rules(character)
return new_string
def createLSystem(iterations, axiom, rules):
string = ""
for _ in range(iterations):
string = processStr(axiom, rules)
axiom = string
return string
def drawLSystem(turtle, lsys, angle, length):
for command in lsys:
if command == 'F':
turtle.forward(length)
elif command == '+':
turtle.left(angle)
elif command == '-':
turtle.right(angle)
yertle = Turtle('turtle')
yertle.speed('fastest')
yertle.shape('turtle')
yertle.color('dark green', 'light green')
sg_string = createLSystem(ITERATIONS, 'F', SGRules)
print(sg_string)
drawLSystem(yertle, sg_string, ANGLE, LENGTH)
for _ in range(2):
yertle.left(ANGLE)
yertle.forward(LENGTH * 2 ** ITERATIONS)
screen = Screen()
screen.mainloop()
Though your original code worked fine in the Python console once I added a transfer to tkinter's event loop at the end to keep the window from closing. 尽管一旦我在末尾向tkinter的事件循环中添加了转移以防止窗口关闭,您的原始代码在Python控制台中的运行情况就很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.