如何在tkinter python gui中用鼠标选择多个对象?

时间:2013-04-01 06:21:38

标签: user-interface python-2.7 tkinter

我正在尝试使用鼠标选择多个对象,就像在Windows中单击并拖动一样。我在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应该返回对象的标签。我怎么能这样做。

谢谢

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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)