how to find tags near to mouse click in tkinter python gui

Question:

How can i identify a tag near to mouse click. here my definition “identify” should identify tag very near to mouse click.

from Tkinter import *
root = Tk()
f=Frame(root)
f.grid()
w=Canvas(f)
line1=w.create_line(50,50,150,150, width=5, tags="line1")
line2=w.create_line(100,100,100,350, width=3, tags="line2")
line3=w.create_line(150,150,150,450, width=3, tags="lines")
w.grid(row=0, column=0)
w.bind("<Button-1>", identify)
def identify(event): ## this should identify the tag near to click

u=Frame(f)
u.grid(row=0, column=1)
root.mainloop()

Thanks

Asked By: lokesh

||

Answers:

Canvas provides a bunch of find_* methods. Here, find_closest fit your need.

def identify(event):
    closest = w.find_closest(event.x,event.y)[0]

Note that if you change the viewport of the canvas (pan, zoom…), you will have to convert from event coordinate to canvas coordinate

def callback(event):
    canvas = event.widget
    x = canvas.canvasx(event.x)
    y = canvas.canvasy(event.y)
    print canvas.find_closest(x, y)

(copied from effbot.org)

Answered By: FabienAndre

Use find_closest and gettags:

def identify(event):
    item = w.find_closest(event.x, event.y)[0]
    tags = w.gettags(item)
    print tags

By the way, you have to define the function before you bind it to the event.

Answered By: A. Rodas

You can directly get the item in the canvas and find its associated tags

def find_item(event):
    item = canvas.find_withtag('current')[0]
    print(canvas.gettags(item))
Answered By: Sharankmp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.