[Tutor] Tkinter, how to retrieve information about an object on canvas

Peter Otten __peter__ at web.de
Thu Nov 15 10:37:12 CET 2012


Matheus Soares da Silva wrote:

> Hello, I would like to be able to get information from a Tkinter canvas
> object. (color, width, tags, root points, etc),
> 
>  I wrote the following function that, with a canvas bind, returns me the
> widget that has been clicked on, the widget is returned as a tuple by the
> find_overlapping method.
> 
> # detecting click
> def Hasclicked(e):
>     global obj
>     global lastClick
>     lastClick = [e.x, e.y]
>     obj = e.widget.find_overlapping(e.x, e.y, e.x, e.y)
> 
>   So, there's any method I can use on 'obj' to get the attributes?

obj is a tuple of ids. You can use canvas.itemcget(id, attribute) to explore 
the properties of the underlying objects

To get (for example) their fill-color:

for id in e.widget.find_overlapping(e.x, e.y, e.x, e.y):
    print canvas.itemcget(id, "fill")

A complete example:

from __future__ import division
import Tkinter as tk
from math import cos, sin, pi

WIDTH = 640
HEIGHT = 480

root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

var = tk.StringVar()
label = tk.Label(root, textvariable=var)
label.pack()

def canvas_click(event):
    x, y = event.x, event.y
    ids = canvas.find_overlapping(x, y, x, y)
    clicked_colors = ", ".join(canvas.itemcget(id, "fill") for id in ids)
    var.set(clicked_colors)

RADIUS = 100
R = 80
CX = WIDTH // 2
CY = HEIGHT // 2

phi = pi/2 # 90 degree
for color in "red", "green", "blue":
    x = int(CX + R*cos(phi))
    y = int(CY - R*sin(phi))
    phi += pi*2/3 # 120 degree

    canvas.create_oval(x-RADIUS, y-RADIUS, x+RADIUS, y+RADIUS, fill=color)

canvas.bind("<Button-1>", canvas_click)
root.mainloop()




More information about the Tutor mailing list