你需要弄清楚由方規定的區域的大小,以便您可以比較下鼠標稍後點擊職位,看看他們是否在裏面。這裏有一個完整的程序,首先允許通過點擊定義正方形的左下角,繪製它,然後每次在矩形區域內單擊鼠標時調用指定的函數。
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()
類型取決於你的方形區域是如何定義的,不是嗎? –