python turtle图形无法绘制

时间:2019-12-02 07:44:18

标签: python turtle-graphics

当我运行以下代码时,它只会弹出一个窗口,并且不会绘制任何图形。

我从参考文献中尝试了一些例子,但是在所有情况下,它都发生了。有人可以帮我解决问题吗?

import turtle
turtle.mainloop()
t = turtle.Turtle()
t.color('red')
t.pensize(10)
t.shape('turtle')

2 个答案:

答案 0 :(得分:0)

查看此处:

https://docs.python.org/3.1/library/turtle.html#turtle.mainloop

启动事件循环-调用Tkinter的 mainloop 函数。 必须是乌龟图形程序中的最后一个语句。如果脚本是在-n模式下(无子进程)从IDLE中运行的,则必须使用该脚本-交互使用龟图形。

因此,您在程序末尾有第二行

在没有mainloop的情况下,我也可以在repl.it中看到红色的Turtle: https://repl.it/@CarstenEggers/Raphael

答案 1 :(得分:0)

不执行任何操作的原因是,您实际上没有告诉“抽屉” t 绘制任何东西。您告诉它要做的所有事情都只是设置说明:要使用哪种颜色,要绘制的大小等等。

尝试运行此代码。注释中的解释:

import turtle
# turtle.mainloop()  # Generally not necessary to run mainloop; can just delete
t = turtle.Turtle()  # Creating a turtle to do drawing
t.color('red')  # Telling it what color to draw
t.pensize(10)  # Telling it what size to draw at
t.shape('turtle')  # What shape turtle draw-er should be: "arrow", "turtle", etc

# Now let's draw something!
t.forward(50)  # Tell turtle to draw in forward direction 50 pixels
t.left(80)  # Tell turtle to turn in-place 80 degrees to left
t.forward(100)  # Draw 100 pixels forward
t.right(90)  # Turn in-place 90 degrees right
t.forward(170)  # Draw 170 pixels forward
# Done drawing!

turtle.exitonclick()  # Tell program to keep picture on screen, exit on click
# Note: See how that's `turtle` and not `t`? That's because we don't want to
# tell our draw-er `t` anything: `t` is just for drawing, it doesn't control
# the larger scope of starting and exiting. If we said `t.exitonclick()`, the
# program would just break at the end, because the draw-er does not know how
# to exit or anything.
# On the the other hand, the module `turtle` (where we get the draw-er and
# everything else from) does know how to handle starting and exiting, so that's
# why we make the call to the module itself instead of the draw-er `t`.