【问题标题】:Is there a way to store circle coordinates and move them around in python turtle?有没有办法存储圆坐标并在 python turtle 中移动它们?
【发布时间】:2022-06-11 02:34:25
【问题描述】:

我知道可以将多边形存储在字典中,因为它们具有确定的坐标,但是有没有办法将圆的坐标存储到字典中以移动它们? get.poly 函数和制作我的 turtle('Shape') 只是制作另一个副本,而不是移动我已经绘制的当前圆圈。对于上下文,我的程序包括检测鼠标单击是否在一个圆圈内,然后从那里获取该圆圈的坐标,并通过另一个鼠标单击将其移动到用户想要的任何位置。以下是我想做的不完整的sn-p

def buttonclick(x, y): # detects mouseclick
    return pen.goto(x, y)

def check(ctr, pt): # check whether the click is within the circle
    if (pt[0] - ctr[0])** 2 + (pt[1] - ctr[1])**2 < 5**2:
        return True

if check((0,5), mouseclick coordinates): # if true, move circle to next click
    # pen = the circle thats detected
    # move circle coordinates to next mouseclick
    # break 

我尝试使用 /u/cdlane 提供的代码如下,这就是我生成新副本的意思

pen.goto(0,0)
pen.pd()
pen.begin_poly()
pen.circle(radius)
pen.end_poly()
shape.addcomponent(pen.get_poly(), 'red', 'black')
screen.register_shape('1', shape)
pen = Turtle(shape = '1')
pen.pu()

函数完全符合我的需要,但使用现有圆圈而不是生成新副本。

【问题讨论】:

    标签: turtle-graphics python-turtle


    【解决方案1】:

    我将建议一个不同的实现来实现你所描述的,而不是修复你的实现。

    圆圈本身就是海龟,点击其中一个会“选中”它。之后单击屏幕上的任意位置将移动它。但是,我们不希望 turtle.onclick()screen.onclick() 同时处于活动状态,因为它们都会被调用,从而导致并发症。下面是我的两只乌龟的例子:

    from turtle import Screen, Turtle
    from functools import partial
    
    selected = None
    
    def on_screen_click(x, y):
        global selected
    
        screen.onclick(None)
    
        selected.goto(x, y)
        outline, fill = selected.color()
        selected.color(fill, outline)
        selected = None
    
        for turtle in screen.turtles():
            turtle.onclick(partial(on_turtle_click, turtle))
    
    
    def on_turtle_click(self, x, y):
        global selected
    
        for turtle in screen.turtles():
            turtle.onclick(None)
    
        selected = self
        outline, fill = selected.color()
        selected.color(fill, outline)
    
        screen.ontimer(partial(screen.onclick, on_screen_click))
    
    screen = Screen()
    
    turtle_1 = Turtle()
    turtle_1.shape('circle')
    turtle_1.color('red', 'black')
    turtle_1.penup()
    
    turtle_2 = turtle_1.clone()
    turtle_2.goto(100, 100)
    
    for turtle in screen.turtles():
        turtle.onclick(partial(on_turtle_click, turtle))
    
    screen.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2013-08-08
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      相关资源
      最近更新 更多