Python 3.x Python支持多次单击事件

Python 3.x Python支持多次单击事件,python-3.x,turtle-graphics,Python 3.x,Turtle Graphics,我正在尝试使用Python turtle制作一个海龟版的8皇后拼图 我已经开始了,但遇到了一个障碍,自定义海龟对象上的单击事件似乎只触发一次。我知道屏幕点击事件会触发多次,所以这是海龟实例的一个特性吗?请问我错过了什么 import turtle screen = turtle.Screen() screen.reset() SIZE = 40 screen.register_shape('box', ((-SIZE/2, SIZE/2), (SIZE/2, SIZE/2), (SIZE/2,

我正在尝试使用Python turtle制作一个海龟版的8皇后拼图

我已经开始了,但遇到了一个障碍,自定义海龟对象上的单击事件似乎只触发一次。我知道屏幕点击事件会触发多次,所以这是海龟实例的一个特性吗?请问我错过了什么

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())

编辑:我可以通过向单击处理程序添加
self.onclick(self.click\u handler)
来解决这个问题,但这似乎是错误的。我确信我见过类似的功能,每次使用时都不需要重新绑定事件。

您的示例应该能够正确运行,我看不出概念上的问题

但海龟身上有个小毛病。有关
onclick
的信息存储在海龟的
\u项
属性中:

self.screen._onclick(self.turtle._item, fun, btn, add)
if self._type in ["image", "polygon"]:
        screen._delete(self._item)
但是,如果将海龟的形状从图像更改为多边形,或者反之亦然,则会破坏
\u item
属性:

self.screen._onclick(self.turtle._item, fun, btn, add)
if self._type in ["image", "polygon"]:
        screen._delete(self._item)
所以你的绑定丢失了。请注意,如果更改行:

self.shape('images/queenlogo40x40.gif')
改为:

self.shape('turtle')
代码工作正常,因为您正在从一个多边形转到另一个多边形,并且
\u项
被保留。因此,在多边形和图像之间切换时,需要在形状更改后添加
self.onclick(self.click\u handler)

我在下面稍微修改了您的代码,以解决几个不相关的问题(例如,修复了Python 3的
super()
调用;删除了
\uu str\uu()
代码中不正确的参数)


你的例子应该运行正常,我看不出概念上的问题

但海龟身上有个小毛病。有关
onclick
的信息存储在海龟的
\u项
属性中:

self.screen._onclick(self.turtle._item, fun, btn, add)
if self._type in ["image", "polygon"]:
        screen._delete(self._item)
但是,如果将海龟的形状从图像更改为多边形,或者反之亦然,则会破坏
\u item
属性:

self.screen._onclick(self.turtle._item, fun, btn, add)
if self._type in ["image", "polygon"]:
        screen._delete(self._item)
所以你的绑定丢失了。请注意,如果更改行:

self.shape('images/queenlogo40x40.gif')
改为:

self.shape('turtle')
代码工作正常,因为您正在从一个多边形转到另一个多边形,并且
\u项
被保留。因此,在多边形和图像之间切换时,需要在形状更改后添加
self.onclick(self.click\u handler)

我在下面稍微修改了您的代码,以解决几个不相关的问题(例如,修复了Python 3的
super()
调用;删除了
\uu str\uu()
代码中不正确的参数)