使用鼠标移动来更新圆的位置会在鼠标快速移动时中断,tkinter-python

我在做一个可拖动的点(一个圆圈)。该代码有效,但是在拖动时,如果鼠标快速移动,该点将停止移动。我已从this code获得帮助以制作此程序。稍后我将把这一点用于其他目的。这是我的完整代码,

from tkinter import *
import sys,os,string,time

class Point():
    def __init__(self,canvas,x,y):
        self.canvas = canvas
        # It could be that we start dragging a widget
        # And release it while its on another
        # Hence when we land on a widget we set self.loc to 1
        # And when we start dragging it we set self.dragged to 1
        self.loc = self.dragged = 0
        self.x = x
        self.y = y
        self.radius = 5
        self.point = canvas.create_oval(self.x-self.radius,self.y-self.radius,self.x+self.radius,self.y+self.radius,fill="green",tag="Point")

        canvas.tag_bind("Point","<ButtonPress-1>",self.down)
        canvas.tag_bind("Point","<ButtonRelease-1>",self.chkup)
        canvas.tag_bind("Point","<Enter>",self.enter)
        canvas.tag_bind("Point","<Leave>",self.leave)

    def down(self,event):
        self.loc = 1
        self.dragged = 0
        event.widget.bind("<Motion>",self.motion)
        canvas.itemconfigure(self.point,fill = "red")

    def motion(self,event):
        root.config(cursor = "exchange")
        cnv = event.widget
        cnv.itemconfigure(self.point,fill = "red")
        self.x,self.y = cnv.canvasx(event.x),cnv.canvasy(event.y)
        got = canvas.coords(self.point,self.x-self.radius,self.y+self.radius)

    def enter(self,event):
        canvas.itemconfigure(self.point,fill="blue")
        self.loc = 1
        if self.dragged == event.time:
            self.up(event)

    def up(self,event):
        event.widget.unbind("<Motion>")
        canvas.itemconfigure(self.point,fill="green")
        self.canvas.update()

    def chkup(self,event):
        event.widget.unbind("<Motion>")
        root.config(cursor = "")
        canvas.itemconfigure(self.point,fill="green")
        if self.loc: # is button released in the same widget as pressed
            self.up(event)
        else:
            self.dragged = event.time

    def leave(self,event):
        self.up(event)

root = Tk()
root.title("Drag and Drop")
canvas = Canvas(root,width = 256,height = 256,borderwidth = 1)
point = Point(canvas,128,128)
canvas.pack()
root.mainloop()
qwweerrttyyuuiioop 回答:使用鼠标移动来更新圆的位置会在鼠标快速移动时中断,tkinter-python

您的问题是,如果将鼠标移出小圆圈的速度快于处理移动的速度,则<Leave>绑定会触发。这将导致<Motion>的绑定被禁用。

我的建议是:a)不要在<Leave>上绑定以禁用绑定,b)在<B1-Motion>上绑定,以便仅在按下按钮时绑定才有效。

本文链接:https://www.f2er.com/3118504.html

大家都在问