Python乌龟ondrag事件与复合形状

时间:2017-04-03 04:04:59

标签: python turtle-graphics

当我注册一个多边形或只有一个组件的复合形状时,我能够使用该形状创建一个乌龟光标,添加一个拖动事件处理程序,并将其拖动到屏幕上。

但是当我用第二个组件注册复合形状时,我再也无法拖动它了:

from turtle import Turtle, Screen, Shape

def simple_polygon(turtle):

    turtle.begin_poly()
    turtle.circle(50)
    turtle.end_poly()
    screen.register_shape("simple_polygon", turtle.get_poly())

    turtle.reset()

def compound_single(turtle):

    shape = Shape("compound")

    turtle.begin_poly()
    turtle.circle(50)
    turtle.end_poly()
    shape.addcomponent(turtle.get_poly(), "blue", "blue")  # component #1
    screen.register_shape("compound_single", shape)

    turtle.reset()

def compound_double(turtle):

    shape = Shape("compound")

    turtle.begin_poly()
    turtle.circle(50)
    turtle.end_poly()
    shape.addcomponent(turtle.get_poly(), "green", "green")  # component #1

    turtle.penup()
    turtle.left(90)
    turtle.forward(25)
    turtle.right(90)
    turtle.pendown()

    turtle.begin_poly()
    turtle.circle(25)
    turtle.end_poly()
    shape.addcomponent(turtle.get_poly(), "yellow", "yellow")  # component #2
    screen.register_shape("compound_double", shape)

    turtle.reset()

def drag_handler(turtle, x, y):
    turtle.ondrag(None)  # disable ondrag event inside drag_handler
    turtle.goto(x, y)
    turtle.ondrag(lambda x, y, turtle=turtle: drag_handler(turtle, x, y))

screen = Screen()

magic_marker = Turtle()
simple_polygon(magic_marker)
compound_single(magic_marker)
compound_double(magic_marker)
magic_marker.hideturtle()

red = Turtle(shape="simple_polygon")
red.color("red")
red.penup()
red.goto(150, 150)
red.ondrag(lambda x, y: drag_handler(red, x, y))

blue = Turtle(shape="compound_single")
blue.penup()
blue.goto(-150, -150)
blue.ondrag(lambda x, y: drag_handler(blue, x, y))

mostly_green = Turtle(shape="compound_double")
mostly_green.penup()
mostly_green.goto(150, -150)
mostly_green.ondrag(lambda x, y: drag_handler(mostly_green, x, y))

screen.mainloop()

您会发现只能拖动生成的三种形状中的两种。注释掉这一行:

shape.addcomponent(turtle.get_poly(), "yellow", "yellow")  # component #2

并且第三个圆圈将全部变为绿色并变得可拖动。

我无法在海龟文档中找到关于复合形状的任何提及,其中多个组件在拖动时不是有效游标。第二个组成部分是完全在第一个组成部分之内,重叠还是在第一个组成部分之外,它没有任何区别。

看一下乌龟代码,我看不出任何区别,让我相信这个问题是在tkinter基础中,并没有在乌龟中正确记录。这个问题是Unix还是OSX特有的?

我错过了什么吗?为什么我不能拖动由多个组件构建的游标?

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为这是当您拖动一个对象时,整个画布都在移动并且看起来好像在移动。

同一件事在Canvas Tkinter中发生。 当您对单击对象时发生的事情进行编程时,整个画布都在等待单击。因此,这意味着如果两个对象都具有onclick事件,则整个操作将无法正常进行。

希望这会有所帮助!