问题
I need some help. I'm working on writing my initials with turtle in python, but for whatever reason I'm unable to make the turtle move. Even when the cursor moves, the turtle still starts in the middle of the screen. Even though I'm using penup() and pendown().
I've pared my code down to this:
import turtle
window = turtle.Screen()
window.bgcolor("red")
def draw_art():
charles = turtle.Turtle()
charles.shape("turtle")
charles.color("yellow")
charles.speed(2)
turtle.penup()
turtle.goto(-100,50)
turtle.pendown()
charles.back(100)
charles.right(90)
charles.forward(100)
charles.right(90)
charles.backward(100)
window.exitonclick()
draw_art()
回答1:
The turtle module presents the programmer with both a functional and an object-oriented interface. You've made the common error of accidentally mixing the two. When you write:
charles = turtle.Turtle()
charles.forward(100)
You're using the object-oriented interface on a turtle created by you. (Good for you!) But this:
turtle.goto(-100, 50)
Invokes the functional interface on the default turtle which was created for you. There's a simple way to avoid this error -- instead of using this statement:
import turtle
use:
from turtle import Turtle, Screen
This locks out the functional interface and only allows the object-oriented one. So your example code would now look like:
from turtle import Turtle, Screen
def draw_art():
charles = Turtle('turtle')
charles.color('yellow')
charles.speed('slow')
charles.penup()
charles.goto(-100, 50)
charles.pendown()
charles.back(100)
charles.right(90)
charles.forward(100)
charles.right(90)
charles.backward(100)
window = Screen()
window.bgcolor('red')
draw_art()
window.exitonclick()
A call like turtle.goto(-100, 50)
will now generate an error: name 'turtle' is not defined
回答2:
def draw_art():
charles = turtle.Turtle()
Let's talk about the why of moving Charles:
Up top, you created an instance of the Turtle class, and set it to the variable charles.
charles is a turtle, yes, but you want to move charles -- he is your instance of this "type" called a turtle.
Hope that helps your understanding! For more, look into OOP in Python.
来源:https://stackoverflow.com/questions/44791295/moving-turtle-in-python