下面是我根据您所描述的实现方式所做的实现。我把它从Tk转移到了turtle中。但是,我引入了低级别的Tk调用来实现缺失的turtle
onmove()
事件处理程序。一旦这个处理程序就位,就变成了管理运动、点击、释放和拖动的问题。请确保首先点击窗口的标题栏使其处于活动状态:
from turtle import Turtle, Screen
MOVING, DRAGGING = range(2)
def move_handler(x, y):
if state != MOVING:
return
onmove(screen, None)
yertle.penup()
yertle.setheading(yertle.towards(x, y))
yertle.goto(x, y)
onmove(screen, move_handler)
def click_handler(x, y):
global state
yertle.onclick(None)
onmove(screen, None)
yertle.onrelease(release_handler)
yertle.ondrag(drag_handler)
state = DRAGGING
def release_handler(x, y):
global state
yertle.onrelease(None)
yertle.ondrag(None)
yertle.onclick(click_handler)
onmove(screen, move_handler)
state = MOVING
def drag_handler(x, y):
if state != DRAGGING:
return
yertle.ondrag(None)
yertle.pendown()
yertle.setheading(yertle.towards(x, y))
yertle.goto(x, y)
yertle.ondrag(drag_handler)
def onmove(self, fun, add=None):
"""
Bind fun to mouse-motion event on screen.
Arguments:
self -- the singular screen instance
fun -- a function with two arguments, the coordinates
of the mouse cursor on the canvas.
Example:
>>> onmove(turtle.Screen(), lambda x, y: print(x, y))
>>> # Subsequently moving the cursor on the screen will
>>> # print the cursor position to the console
>>> screen.onmove(None)
"""
if fun is None:
self.cv.unbind('<Motion>')
else:
def eventfun(event):
fun(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale)
self.cv.bind('<Motion>', eventfun, add)
screen = Screen()
screen.setup(500, 600)
screen.screensize(1920, 1080)
yertle = Turtle('turtle')
yertle.speed('fastest')
state = MOVING
onmove(screen, move_handler)
yertle.onclick(click_handler)
screen.mainloop()
onmove()
事件的实现来自于我在
Python turtle中查找光标当前位置 的答案中,如果您访问时觉得有帮助,请随手点个赞。 (就像您的
drag_handler()
是从我在
Turtle freehand drawing 的答案中得到的一样,如果您还没有点赞,请随意点赞。)