Google ColaboratoryでPythonを使用し画像や図形を作成できるTurtleモジュールを試してみます。
■Python
Google Colaboratory(Google Colab),Python3.7.10
■Turtleモジュールで画像や図形を作成する
では、Google ColaboratoryでTurtleモジュールを使用し、画像や図形を作成するためにスクリプトを書いていきます。
■コード
import turtle turtle.forward(110)
importでTurtleモジュールを呼び出します。今回はforward()関数を使用し、タートル(亀)を前方に移動してみます。移動する際は関数の括弧内に引数,パラメータとして数値(整数または浮動小数点数)を渡します。これで指定された距離だけタートル(亀)が前方に移動します。
■実行・検証
では、このスクリプトを実行してみます。
---------------------------------------------------------------------------
TclError Traceback (most recent call last)
in ()
1 import turtle
----> 2 turtle.forward(110)
5 frames
/usr/lib/python3.7/turtle.py in forward(distance)
/usr/lib/python3.7/turtle.py in __init__(self, shape, undobuffersize, visible)
3810 visible=_CFG["visible"]):
3811 if Turtle._screen is None:
-> 3812 Turtle._screen = Screen()
3813 RawTurtle.__init__(self, Turtle._screen,
3814 shape=shape,
/usr/lib/python3.7/turtle.py in Screen()
3660 else return the existing one."""
3661 if Turtle._screen is None:
-> 3662 Turtle._screen = _Screen()
3663 return Turtle._screen
3664
/usr/lib/python3.7/turtle.py in __init__(self)
3676 # preserved (perhaps by passing it as an optional parameter)
3677 if _Screen._root is None:
-> 3678 _Screen._root = self._root = _Root()
3679 self._root.title(_Screen._title)
3680 self._root.ondestroy(self._destroy)
/usr/lib/python3.7/turtle.py in __init__(self)
432 """Root class for Screen based on Tkinter."""
433 def __init__(self):
--> 434 TK.Tk.__init__(self)
435
436 def setupcanvas(self, width, height, cwidth, cheight):
/usr/lib/python3.7/tkinter/__init__.py in __init__(self, screenName, baseName, className, useTk, sync, use)
2021 baseName = baseName + ext
2022 interactive = 0
-> 2023 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
2024 if useTk:
2025 self._loadtk()
TclError: no display name and no $DISPLAY environment variable実行してみると、TclErrorというエラーが発生しました。エラーの内容を確認すると「表示名がなく、環境変数$DISPLAYもない」ということで、エラーの原因を調べてみると、Google ColaboratoryではTurtleモジュールが動かないということが判明しました。


コメント