以下代码呈现一个跟随光标的矩形,并返回矩形内元素的元素 ID 列表。当鼠标在画布中按下、移动和释放时,它使用绑定。然后,我保留了一个带有画布标识符的元素列表,并使用它从选定的 ID 列表中查找对象。
# used to record where dragging from
originx,originy = 0,0
canvas.bind("<ButtonPress-1>", __SelectStart__)
canvas.bind("<B1-Motion>", __SelectMotion__)
canvas.bind("<ButtonRelease-1>", __SelectRelease__)
# binding for drag select
def __SelectStart__(self, event):
oiginx = canvas.canvasx(event.x)
originy = canvas.canvasy(event.y)
selectBox = canvas.create_rectangle(originx,originy,\
originx,originy)
# binding for drag select
def __SelectMotion__(self, event):
xnew = canvas.canvasx(event.x)
ynew = canvas.canvasy(event.y)
# correct cordinates so it gives (upper left, lower right)
if xnew < x and ynew < y:
canvas.coords(selectBox,xnew,ynew,originx,originy)
elif xnew < x:
canvas.coords(selectBox,xnew,originy,originx,ynew)
elif ynew < y:
canvas.coords(selectBox,originx,ynew,xnew,originy)
else:
canvas.coords(selectBox,originx,originy,xnew,ynew)
# binding for drag select
def __SelectRelease__(self, event):
x1,y1,x2,y2 = canvas.coords(selectBox)
canvas.delete(selectBox)
# find all objects within select box
selectedPointers = []
for i in canvas.find_withtag("tag"):
x3,y3,x4,y4 = canvas.coords(i)
if x3>x1 and x4<x2 and y3>y1 and y4<y2:
selectedPointers.append(i)
Callback(selectedPointers)
# function to receive IDs of selected items
def Callback(pointers):
print(pointers)