Tkinter, getting canvas-object, how?

Rafał Wysocki rafal.wysocki at gmail.com
Sat Apr 19 04:15:13 EDT 2008


skanem... at yahoo.se napisał(a):
> so i load a gif onto a canvas and when i click the canvs i want to get
> the color of the pixel that is clicked.
> so i need to ge the object im clicking.
> i was told in another thread to use find_withtag or find_closest but
> it is not working, maybe im using the
> method on the wrong object.
> how do i do this?
> and how do i then get specifics about that object, ie the pixel-color?
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
>     return self.func(*args)
>   File "C:\Users\saftarn\Desktop\pythonkod\mapexperiments
> \mapgetobject.py", line 17, in callback
>     undermouse=find_closest(master.CURRENT)
> NameError: global name 'find_closest' is not defined
>
> from Tkinter import *
>
> master = Tk()
>
> w = Canvas(master, width=400, height=625)
> w.pack(expand = YES, fill = BOTH)
>
> mapq = PhotoImage(file = 'C:\Users\saftarn\Desktop\Maps\provinces-of-
> sweden.gif')
> w.create_image(30, 30, image = mapq, anchor = NW)
>
> def key(event):
>     print "pressed", repr(event.char)
>
> def callback(event):
>     clobj=event.widget
> ##    undermouse=find_withtag(master.CURRENT)
>     undermouse=find_closest(master.CURRENT)
>     print repr(undermouse)
>
> w.bind("<Key>", key)
> w.bind("<Button-1>", callback)
> w.pack()
>
> mainloop()

from Tkinter import *

master = Tk()

w = Canvas(master, width=400, height=625)
w.pack(expand = YES, fill = BOTH)

mapq = PhotoImage(file = 'img.gif')
_id = w.create_image(0, 0, image = mapq, anchor = NW)

objects = {} # map id to object
objects[_id] = mapq

def key(event):
    print "pressed", repr(event.char)

def callback(event):
    x, y = w.canvasx(event.x), w.canvasy(event.y) # Translates a
window x,y coordinates to a canvas coordinate
    _id = w.find_closest(x,y)[0] # Returns tuple containing the object
id
    obj = objects[_id]           # Finds object with given id
    print 'color: %s' % obj.get(int(x), int(y))

w.bind("<Key>", key)
w.bind("<Button-1>", callback)
w.pack()

mainloop()



More information about the Python-list mailing list