在Python的Turtle庫中,可以使用turtle.getcanvas().winfo_pointerpos()
來獲取鼠標在畫布上的位置,然后根據這個位置來進行相應的操作。
例如,以下代碼會在鼠標點擊時繪制一個圓:
import turtle
def draw_circle(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor("red")
turtle.end_fill()
turtle.speed(0)
turtle.hideturtle()
turtle.getcanvas().winfo_toplevel().bind("<Button-1>", lambda event: draw_circle(event.x, event.y))
turtle.mainloop()
在這個代碼中,我們定義了一個draw_circle
函數,它接受鼠標點擊的位置作為參數,并使用Turtle庫繪制一個紅色的圓。然后,我們使用turtle.getcanvas().winfo_toplevel().bind
方法將鼠標點擊事件綁定到draw_circle
函數上。當用戶點擊畫布時,就會調用這個函數,并繪制一個圓。