Feb-10-2021, 09:13 PM
(This post was last modified: Feb-10-2021, 09:13 PM by deanhystad.)
The main purpose of a class is to define a template for reusable code. Your ship class can never be used anywhere that doesn't have a canvas named c1, a main window named r, and worst of all, an instance of ship named s. It is rare that a class references an instance of itself unless it is a singleton, or maintains a list of instances for some reason (pool allocation for example). My inclination is to write the code like this:
from tkinter import * class Ship(): def __init__(self, parent, wide, high): self.canvas = Canvas(parent, width=wide, height=high) self.canvas.pack() self.img = PhotoImage(file = "test_image.png") img_wide = self.img.width() img_high = self.img.height() self.xmax = wide - img_wide self.ymax = high - img_high self.x = int((wide - img_wide) / 2) self.y = int((high - img_high) / 2) self.img_id = self.canvas.create_image(self.x, self.y, anchor=NW, image=self.img) def move(self, x, y): x = max(-self.x, min(x, self.xmax - self.x)) y = max(-self.y, min(y, self.ymax - self.y)) self.x += x self.y += y self.canvas.move(self.img_id, x, y) root = Tk() ship = Ship(root, 500, 400) root.bind("<Right>", lambda event: ship.move(x=5, y=0)) root.bind("<Left>", lambda event: ship.move(x=-5, y=0)) root.bind("<Up>", lambda event: ship.move(x=0, y=-5)) root.bind("<Down>", lambda event: ship.move(x=0, y=5)) root.mainloop()I also changed things so the ship starts out in the middle of the sea (canvas) and is prevented from sailing off the edge.