【发布时间】:2018-10-10 20:44:54
【问题描述】:
我正在尝试使用鼠标绘制海龟,我得到了下面的演示代码,但在鼠标移动期间有时光标会跳转:
#!/usr/bin/env python
import turtle
import sys
width = 600
height = 300
def gothere(event):
turtle.penup()
x = event.x
y = event.y
print "gothere (%d,%d)"%(x,y)
turtle.goto(x,y)
turtle.pendown()
def movearound(event):
x = event.x
y = event.y
print "movearound (%d,%d)"%(x,y)
turtle.goto(x,y)
def release(event):
print "release"
turtle.penup()
def circle(x,y,r):
turtle.pendown()
turtle.goto(x,y)
turtle.circle(r)
turtle.penup()
return
def reset(event):
print "reset"
turtle.clear()
#------------------------------------------------#
sys.setrecursionlimit(90000)
turtle.screensize(canvwidth=width, canvheight=height, bg=None)
turtle.reset()
turtle.speed(0)
turtle.setup(width, height)
canvas = turtle.getcanvas()
canvas.bind("<Button-1>", gothere)
canvas.bind("<B1-Motion>", movearound)
canvas.bind("<ButtonRelease-1>", release)
canvas.bind("<Escape>",reset)
screen = turtle.Screen()
screen.setworldcoordinates(0,height,width,0)
screen.listen()
turtle.mainloop()
#------------------------------------------------#
查看下面的 gif 以了解实际行为:
不确定是否有任何 API 调用错误!
【问题讨论】:
-
sys.setrecursionlimit(90000)对我来说很可疑。如果您因为之前遇到异常错误且堆栈跟踪很长而添加了这一点,我怀疑该错误与您现在遇到的问题有关。 -
看起来在海龟到达光标位置之前移动鼠标时会发生这种情况。当您单击时,您可以看到海龟向光标移动 - 如果您在鼠标到达光标之前开始移动鼠标,则在您拖动时它不会画一条线,一旦您松开鼠标按钮,您将得到那种奇怪的跳跃行为。
-
如果我删除
setrecursionlimit行,那么这段代码偶尔会产生一个重复输入movearound的回溯。我怀疑这是因为movearound调用goto,后者调用update,它检查鼠标更新并可能再次调用movearound。如果 Tkinter 并不总是按照接收到鼠标事件的顺序评估鼠标事件,这可能解释了海龟的抖动运动。 effbot.org/tkinterbook/widget.htm 表示在回调中使用update()会导致“恶劣的竞争条件”,这似乎正是这里发生的情况。 -
(将上述评论作为评论而不是答案发布,因为我没有可以解决问题的快速解决方案;最好的办法就是不要在函数绑定到画布。但如果他不这样做,OP 将如何实现他想要的行为?)
-
添加
self.tracer(2,0)似乎可以解决您的问题!