Python Forum
how do i find the canvas location of an object?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how do i find the canvas location of an object?
#2
A new record for most things wrong in 16 lines. I'm guessing this is the result of a lot of frustrated thrashing.

To start with, you cannot create a class named Image if you want to use a class named Image from the PIL library. You should never see two lines like this in any Python file.
from PIL import ImageTk,Image
..
class Image:
By defining a class named "Image" you have made it that you cannot use the Image class from PIL library. Even in this case where you don't need the PIL.Image class it is a bad idea to name classes after commonly used classes or modules in Python.

So mship is not an Image. Well, it is an Image, but it is your Image, not the kind of Image that you can add to a label or a canvas. In fact there are very few things that your Image can do. All it has is a couple of attributes. No methods are defined.

Even if mship was a PIL.Image or a tkinter.PhotoImage, you could not get it's bounding box. Image or PhotoImage is like "red". It is paint. You can paint an image as part of a button, or a label or you can paint an image on a canvas. But an image is not a thing that can be moved around or located. You cannot pack() and image. Image/PhotoImage is not a widget or a canvas object. It is just an interesting paint pattern.

The image doesn't become anything all that interesting until you use it. This code creates a canvas object that looks like your image. canvas.create_image() returns a handle to the newly created object. An ID that you can use to manipulate the object.
self.id =  canvas.create_image(120,0,anchor=NW,image=self.img)
Using the ID you can move the image around on the canvas. You can also use the ID to get the coordinates of the image or get the image's, I mean object's, bounding box.
import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)

img = tk.PhotoImage(file='ttt_x.png')
id = canvas.create_image(0, 0, image=img)

print(canvas.bbox(id))
print(canvas.coords(id))
print(canvas.bbox(img)
Output:
(-40, -40, 40, 40) [0.0, 0.0] None
Notice that bbox(id) returns a rectangle. bbox(img) returns None. This is because "img" is not a canvas object, id is. "img" just tells the canvas how to paint the object referenced by id.
Reply


Messages In This Thread
RE: how do i find the canvas location of an object? - by deanhystad - Mar-03-2021, 05:32 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Resizing image inside Canvas (with Canvas' resize) Gupi 2 25,165 Jun-04-2019, 05:05 AM
Last Post: Gupi
  [Tkinter] Problem loading an image from directory into a Canvas object tiotony 3 3,898 Sep-02-2018, 06:47 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020