Home > other >  Python turtle function - receiving an error I can't make sense of
Python turtle function - receiving an error I can't make sense of

Time:06-11

When running the below code I am receiving this error. Anyone any ideas, I have followed an example set by a tutor and made it my own but mine doesn't run.

Traceback (most recent call last):
  File "main.py", line 74, in <module>
    timmy.color(random_color)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/turtle.py", line 2217, in color
    pcolor = self._colorstr(pcolor)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/turtle.py", line 2697, in _colorstr
    return self.screen._colorstr(args)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/turtle.py", line 1153, in _colorstr
    if len(color) == 1:
TypeError: object of type 'function' has no len()
import turtle
import random

timmy = turtle.Turtle()
turtle.colormode(255)
timmy.shape("turtle")
timmy.color("red")

turtle_heading = [0, 90, 180, 270]

def random_color():
  r = random.randint(0, 255)
  g = random.randint(0, 255)
  b = random.randint(0, 255)
  random_color(r, g, b)
  return random_color


for i in range(200):
  timmy.setheading(random.choice(turtle_heading))
  timmy.color(random_color)
  timmy.forward(30)

CodePudding user response:

You seem to have gotten variables and functions confused. Maybe from VBA or similiar.

In python, a variable is either a function or a value, never both.

At then end of your random_color() you call random_color with the arguments (r,g,b), which will give you an error when executed, as your function doesn't take arguments. Then you return the function itself.

What you probably wanted to do was to return the tuple (r, g, b) which you can do by replacing the last two lines of the function with return (r, g, b) and then calling it with random_color() in your timmy.color().

Your current error there happens because you pass it the function without executing it, so it complains that the function-type object you passed has no length (as that is required by timmy.color)

  • Related