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?
#5
A class would be nice. At a minimum it keeps a reference to the image around without adding lots of extra image variables. You could add some methods to make it more useful. Here's one of your early posts modified to use an image class with collision detection.
import tkinter as tk
 
class CanvasImage():  
    def __init__(self, canvas, x, y, file):
        self.canvas = canvas
        self.img = tk.PhotoImage(file=file)
        self.id = canvas.create_image(x, y, image=self.img)

    def bounds(self):
        return self.canvas.bbox(self.id)

    def coords(self):
        return self.canvas.coords(self.id)

    def move(self, dx, dy):
        self.canvas.move(self.id, dx, dy)

    def moveto(self, x, y):
        self.canvas.moveTo(self.id, x, y)

    def collide(self, object):
        a = self.bounds()
        b = object.bounds()
        if b[0] > a[2] or b[2] < a[0] or b[1] > a[3] or b[3] < a[1]:
            return False
        return True

def move_ship(ship, dx, dy):
    ship.move(dx, dy)
    if ship.collide(planet):
        quit()

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

ship = CanvasImage(canvas, 40, 40, 'ttt_x.png')
planet = CanvasImage(canvas, 200, 200, 'ttt_o.png')

root.bind("<Right>", lambda e: move_ship(ship, 5, 0))
root.bind("<Left>",  lambda e: move_ship(ship, -5, 0))
root.bind("<Up>",    lambda e: move_ship(ship, 0, -5))
root.bind("<Down>",  lambda e: move_ship(ship, 0 , 5))
Reply


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

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Resizing image inside Canvas (with Canvas' resize) Gupi 2 25,160 Jun-04-2019, 05:05 AM
Last Post: Gupi
  [Tkinter] Problem loading an image from directory into a Canvas object tiotony 3 3,896 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