จะเลือกวัตถุหลายชิ้นด้วยเมาส์ใน tkinter python gui ได้อย่างไร

ฉันกำลังพยายามเลือกหลายวัตถุโดยใช้เมาส์เหมือนกับใน windows คลิกแล้วลาก ฉันใช้ tkinter ใน python เพื่อสร้าง 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 บางอย่างควรส่งคืนแท็กของวัตถุ ฉันจะทำสิ่งนี้ได้อย่างไร

ขอบคุณ


person lokesh    schedule 01.04.2013    source แหล่งที่มา


คำตอบ (2)


บันทึกพิกัดในเหตุการณ์แบบกดปุ่มลง จากนั้นในเหตุการณ์แบบกดปุ่มให้ใช้ find_enclosed หรือ find_overlapping ของ canvas เพื่อค้นหารายการทั้งหมดที่อยู่ในขอบเขต

person Bryan Oakley    schedule 01.04.2013

รหัสต่อไปนี้แสดงสี่เหลี่ยมที่ตามหลังเคอร์เซอร์และส่งกลับรายการ ID องค์ประกอบขององค์ประกอบภายในสี่เหลี่ยม โดยจะใช้การผูกเมื่อกดเมาส์ภายในแคนวาส เมื่อเคลื่อนไหว และเมื่อปล่อยออกมา จากนั้น ฉันเก็บรายการองค์ประกอบไว้พร้อมกับตัวระบุ Canvas และใช้สิ่งนั้นเพื่อสำรองการค้นหาออบเจ็กต์จากรายการ 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)
person cweb    schedule 06.07.2021