Mar-03-2021, 03:03 PM
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))