3

我正在尝试使用鼠标选择多个对象,就像在窗口中单击并拖动一样。我在 python 中使用 tkinter 来构建这个 gui。我正在创建对象,如下面的代码所示。

import Tkinter as tk
from Tkinter import *

root = Tk()
w= Canvas(root, width=800, height=768)
w.grid()
w.create_line(200,200,300,300, width=3, tags="line1")
w.create_oval(150,100,170,300, fill="red", tags="oval")

mainloop()

我想要做的是,如果我将鼠标拖到多个对象上,一些 def 应该返回对象的标签。我怎样才能做到这一点。

谢谢

4

2 回答 2

2

保存按钮按下事件的坐标,然后在按钮按下事件上使用画布的find_enclosedfind_overlapping方法查找该区域所包围的所有项目。

于 2013-04-01T10:51:51.097 回答
0

以下代码呈现一个跟随光标的矩形,并返回矩形内元素的元素 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)
于 2021-07-06T04:18:15.610 回答