0

If I click on each turtle, I want it to function separately. But when I clicked on the turtle, they say:'ValueError: -142.0 is not in list.' I want to click the turtle but it returns the location of the mouse. What should I do?

import turtle as t
import random

tt=[]
num=[]

def leftclick(self,x):
    if num[tt.index(self)]==0:
        self.hideturtle()
    else:
        self.color('red')

for i in range(10):
    for j in range(10):
        tt.append(t.Turtle())
        tt[i*10+j].speed(0)
        tt[i*10+j].goto(-260+j*55,260-i*55)
        num.append(random.choice([0,0,0,0,0,0,0,0,0,1]))
        tt[i*10+j].onclick(leftclick)

onclilck(leftclick) Is there anything wrong?

Jiwon2
  • 3
  • 1
  • Did you look up the parameters to the [`onclick` callback](https://docs.python.org/3/library/turtle.html#turtle.onclick)? "`fun` – a function with two arguments which will be called with the coordinates of the clicked point on the canvas", in other words, `x` and `y`, not `self` and `x`. – ggorlen May 27 '23 at 15:16

1 Answers1

0

The function that you pass to onclick() has a predefined signature (arguments and return value) that you can't change to match your needs. However, we can wrap it (via lambda or the partial() routine) to get the behavior we want:

from turtle import Screen, Turtle
from random import choice
from functools import partial

FREQUENCY = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

turtles = []
numbers = []

def leftclick(self, x, y):
    if numbers[turtles.index(self)] == 0:
        self.hideturtle()
    else:
        self.color('red')

screen = Screen()

for i in range(10):
    for j in range(10):
        turtle = Turtle()
        turtle.speed('fastest')
        turtle.goto(-260 + j*55, 260 - i*55)
        turtle.onclick(partial(leftclick, turtle))

        turtles.append(turtle)
        numbers.append(choice(FREQUENCY))

screen.mainloop()
cdlane
  • 40,441
  • 5
  • 32
  • 81