正常我们使用Turtle海龟画图,只需要安装PythonTurtle库就行了。
但在 Jupyter中,因为是在web网页上,所以还需要安装别的,所以用的是 ipyturtle3 库,安装的时候会把依赖库都安装上。
注意:不是 ipyturtle 而是 ipyturtle3,ipyturtle是旧的了。
普通安装
1
| pip install PythonTurtle
|
使用举例:
1 2 3 4 5 6 7 8 9 10 11 12
|
import turtle as t
for x in range(6): for i in range(4): t.forward(50) t.left(90) t.left(60)
t.done()
|
Jupyter中普通安装
就是前面导入的库不同,需要初始化一下环境。用到canvas。
下面基础画图的代码,就基本上可以用一样的。
使用举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import ipyturtle3 as turtle from ipyturtle3 import hold_canvas
myCanvas = turtle.Canvas(width=500,height=300) myTS = turtle.TurtleScreen(myCanvas)
myTS.clear() t = turtle.Turtle(myTS) display(myCanvas)
for x in range(6): for i in range(4): t.forward(50) t.left(90) t.left(60)
|
官方页面中的例子
官方页面:https://pypi.org/project/ipyturtle3/
例子(让gpt中文注释了下)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| import ipyturtle3 as turtle from ipyturtle3 import hold_canvas
myCanvas=turtle.Canvas(width=500,height=250) display(myCanvas)
myTS=turtle.TurtleScreen(myCanvas) myTS.clear() myTS.bgcolor("lightgreen")
bob=turtle.Turtle(myTS) jess=turtle.Turtle(myTS,isHolonomic=True) jess.shape("square") bob.shape("turtle")
myTS.delay(200)
bob.forward(50) bob.left(90) bob.forward(50) bob.left(90) bob.forward(50) bob.left(90) bob.forward(50)
jess.moveleft(200) jess.moveup(100) jess.moveright(100) jess.movedown(100) jess.turnright(45) jess.turn(-45) jess.distance_at_angle(50,45)
myTS.clear()
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow'] t = turtle.Turtle(myTS) myTS.bgcolor('black') for x in range(50): with(hold_canvas(myCanvas)): t.pencolor(colors[x%6]) t.width(x//100 + 1) t.forward(x) t.left(59)
|