Search code examples
pythonpython-3.xmacosturtle-graphicspython-turtle

Failing to run Turtle Graphics program on MacOS


I'm a Python newbie working on my first Turtle Graphics program.

This is what I have at the moment

import turtle

def draw_square():
    window = turtle.Screen()
    window.bgcolor("red")

    brad = turtle.Turtle()
    brad.forward(100)

    window.exitonclick()

draw_square()

This code works perfectly on my friend's Windows laptop: windows However, problem arises when we tried to run it on my Macbook. The issue we were facing is that Python Turtle Graphics displays nothing as below: macos

Why can't my program run normally on MacOS? And how can I resolve this issue?


Solution

  • This is a known issue that arises due to an incompatibility between MacOS and Tkinter, on which Turtle is based. In the terminal, use the following code:

    brew install tcl-tk
    env \
      PATH="$(brew --prefix tcl-tk)/bin:$PATH" \
      LDFLAGS="-L$(brew --prefix tcl-tk)/lib" \
      CPPFLAGS="-I$(brew --prefix tcl-tk)/include" \
      PKG_CONFIG_PATH="$(brew --prefix tcl-tk)/lib/pkgconfig" \
      CFLAGS="-I$(brew --prefix tcl-tk)/include" \
      PYTHON_CONFIGURE_OPTS="--with-tcltk-includes='-I$(brew --prefix tcl-tk)/include' --with-tcltk-libs='-L$(brew --prefix tcl-tk)/lib -ltcl8.6 -ltk8.6'" \
      pyenv install 3.8.13