【问题标题】:Is there a way to avoid the recursion limit in my Turtle-program?有没有办法避免我的 Turtle 程序中的递归限制?
【发布时间】:2021-08-07 19:59:04
【问题描述】:
import turtle
from turtle import Turtle


WIDTH = 1000
HEIGHT = 1000

#Screen setup
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title(" " *150  + "Test_GIU")
screen.bgcolor("black")
screen.setup(1000, 1000)

#Pen
pen = Turtle("circle")
pen.pensize = 5
pen.color("green")
pen.speed(-1)


def dragging(x, y):  # These parameters will be the mouse position
    pen.ondrag(None)
    pen.setheading(pen.towards(x, y))
    pen.goto(x, y)
    pen.ondrag(dragging)

def click_on_c():
    screen.reset()
    pen = Turtle("circle")
    pen.pensize = 5
    pen.color("green")
    pen.speed(-1)
    pen.ondrag(dragging)


def main():  # This will run the program
    turtle.listen()    
    
    pen.ondrag(dragging)  # When we drag the turtle object call dragging
    turtle.onkeypress(click_on_c, "c")
    screen.mainloop()  # This will continue running main()    

main()

这是我的代码,我对它很陌生,所以它不是很好,但它是我的第一个真正的项目。我已经尝试增加递归限制,但即使我将其设置为 10000,它也会崩溃。我还尝试使用 try 和 exept 块来捕获错误,但它也不起作用。

【问题讨论】:

  • 您可能只需要每支笔调用一次ondrag...
  • ^^ 删除所有ondrag 调用,除了main 中的调用。注意:mainloop() 上的注释不正确(它不会重复执行main -- 它处理监视事件队列)
  • @trincot ,我尝试将其移除,但没有那些 ondrag 调用,在我重置海龟后,我实际上根本无法移动它。

标签: python recursion turtle-graphics


【解决方案1】:

让我们尝试一个更简单的设计,而不是调用 screen.reset() 并重新创建海龟,而是调用 pen.reset() 来清除绘图:

from turtle import Screen, Turtle

WIDTH = 1000
HEIGHT = 1000

def dragging(x, y):  # Parameters are the mouse position
    pen.ondrag(None)
    pen.setheading(pen.towards(x, y))
    pen.goto(x, y)
    pen.ondrag(dragging)

def click_on_c():
    pen.reset()
    pen.pensize = 5
    pen.color("green")
    pen.speed('fastest')

# Screen setup
screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Test_GUI")
screen.bgcolor("black")

# Pen
pen = Turtle("circle")
pen.pensize = 5
pen.color("green")
pen.speed('fastest')
pen.ondrag(dragging)

screen.onkeypress(click_on_c, "c")
screen.listen()

screen.mainloop()

在调用 reset() 后,我们必须重置笔的某些方面,因为该调用会将设置清除回默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多