【问题标题】:How can I import the Turtle Module in a class?如何在课程中导入 Turtle 模块?
【发布时间】:2019-05-23 01:30:17
【问题描述】:

我在 python 中绘制分形树,这是我的方法(它有效):

def fractal(length):
    if lenght < 1:
        return
    else:
        turtle.forward(length)
        turtle.left(30)
        fractal(length*0.67)
        turtle.right(60)
        fractal(length*0.67)
        turtle.left(30)
        turtle.backward(length)

现在我正在尝试在一个类中实现这一点,但我不知道应该如何使用海龟命令来实现这一点。

我是编码新手,所以请不要对我的代码过分苛责。

我尝试过这样的事情:

class fractalTree():

from turtle import *

def __init__(self, angle, factor):
    self.angle = angle
    self.factor = factor

def fractal(self, length):
    if length < 1:
        return
    else:
        self.turtle.forward(length)
        self.turtle.left(self.angle)
        fractal(length * self.factor)
        self.turtle.right(self.angle * 2)
        fractal(length * self.factor)
        self.turtle.left(self.angle)
        self.turtle.backward(length)

test = fractalTree(14, 2/3)
test.fractal(100)

【问题讨论】:

  • 您的具体问题是什么?您是否尝试过将此代码集成到使用类的更大的东西中?或者你只是为了使用一个类而使用一个类?请给我们一个更大的图景!
  • 我只是想为了使用一个类而使用一个类。我的确切问题是我不知道如何在一个类中导入海龟模块。
  • 您不必在类中导入任何内容。只需按照您的方式继续导入turtle,在脚本开头使用import turtle
  • 非常感谢。它现在可以工作了,我很高兴:)

标签: python class turtle-graphics


【解决方案1】:

有几种方法可以解决这个问题。您的自定义类可以包含一只乌龟:

from turtle import Screen, Turtle

class fractalTree():

    def __init__(self, angle, factor):
        self.angle = angle
        self.factor = factor
        self.turtle = Turtle()

    def fractal(self, length):
        if length < 1:
            return

        self.turtle.forward(length)
        self.turtle.left(self.angle)
        self.fractal(length * self.factor)
        self.turtle.right(self.angle * 2)
        self.fractal(length * self.factor)
        self.turtle.left(self.angle)
        self.turtle.backward(length)

screen = Screen()

screen.mode('Logo')  # being lazy, make the tree upright

test = fractalTree(30, 2 / 3)

screen.tracer(False)
test.fractal(100)
screen.tracer(True)

screen.exitonclick()

或者,您的自定义类可以变成乌龟:

class fractalTree(Turtle):

    def __init__(self, angle, factor):
        super().__init__()
        self.angle = angle
        self.factor = factor

    def fractal(self, length):
        if length < 1:
            return

        self.forward(length)
        self.left(self.angle)
        self.fractal(length * self.factor)
        self.right(self.angle * 2)
        self.fractal(length * self.factor)
        self.left(self.angle)
        self.backward(length)

或者,您可以按照自己的方式做,让您的自定义类只使用海龟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2020-05-19
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2020-06-20
    相关资源
    最近更新 更多