在python tu中定义区域

2024-10-01 11:22:14 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我的目标是让一个函数在我点击海龟屏幕上的某个区域时发生。 所以当我的乌龟画了一个正方形,我在方块内点击,我需要一些事情发生。在

示例:

turtle.onscreenclick(turtle.goto)

for i in range(4):
      turtle.forward(30)
      turtle.left(90)

if turtle.position() == (within square region):
      Activate function() 

Tags: 函数in区域示例目标for屏幕range
2条回答

你需要计算出正方形所定义的区域的范围,这样以后你就可以比较鼠标点击的位置,看看它们是否在里面。这是一个完整的程序,它首先允许通过单击来定义正方形的左下角,绘制它,然后每次在矩形区域内单击鼠标时调用指定的函数。在

import turtle

def draw_square(x, y):
    global target_region

    turtle.penup()
    turtle.goto(x, y)
    turtle.setheading(0)
    turtle.pendown()
    square = []
    for i in range(4):
        square.append(turtle.pos())  # Save turtle coords
        turtle.forward(30)
        turtle.left(90)

    # Find min and max coordinates of region
    min_x = min(square, key=lambda p: p[0])[0]
    min_y = min(square, key=lambda p: p[1])[1]
    max_x = max(square, key=lambda p: p[0])[0]
    max_y = max(square, key=lambda p: p[1])[1]
    target_region = [min_x, min_y, max_x, max_y]

    turtle.hideturtle()
    turtle.onscreenclick(check_click)  # Switch to next event handler

def check_click(x, y):
    if (target_region[0] <= x <= target_region[2] and
        target_region[1] <= y <= target_region[3]):  # Within square region?
        within_square_region_function()  # Call activate function

def within_square_region_function():
    print('clicked in square')

turtle.onscreenclick(draw_square)  # Set initial event handler
turtle.mainloop()

如果您的意思是只允许goto进入正方形:

import turtle

def goto_inside(x, y):
    if 0 <= x <= 30 and 0 <= y <= 30:
        turtle.goto(x, y)

turtle.onscreenclick(goto_inside)

# draw a square 30x30
for i in range(4):
    turtle.forward(30)
    turtle.left(90)

# turtle.mainloop()

相关问题 更多 >