I'm trying to make a turtle version of the 8-Queens Puzzle using Python Turtle.
I've make a start, but have hit a block with the fact that the click event on a custom Turtle object seems to only fire once. I know screen click events fire multiple times, so is this a feature of Turtle instances? What am I missing please?
import turtle
screen = turtle.Screen()
screen.reset()
SIZE = 40
screen.register_shape('box', ((-SIZE/2, SIZE/2), (SIZE/2, SIZE/2), (SIZE/2, -SIZE/2), (-SIZE/2, -SIZE/2)))
screen.register_shape('images/queenlogo40x40.gif')
class Box(turtle.Turtle):
def __init__(self, x=0, y=0, place_color='green'):
super(Box, self).__init__()
self.place_color = place_color
self.speed(0)
self.penup()
self.shape("box")
self.color(place_color)
self.setpos(x, y)
self.has_queen = False
self.onclick(self.click_handler)
def click_handler(self, x, y):
print("start:" , self.has_queen)
if self.has_queen:
self.shape('box')
self.has_queen = False
else:
self.shape('images/queenlogo40x40.gif')
self.has_queen = True
print("end:" , self.has_queen)
def __str__(self):
""" Print piece details """
return "({0}, {1}), {2}".format(self.xcor(), self.ycor(), self.place_color())
Edit: I can fix this by adding self.onclick(self.click_handler) to the click handler, but that just seems wrong. I'm sure I've seen similar functionality without needing to rebind the event each time it's used.