I wanted to create a chess program using OOP. So I made a superclass Pieces
, a subclass Bishop
, and a UI class GameUI
. I created a canvas in the class GameUI. I wanted, that when I instantiate an object bishop in the class GameUI
, it shows an Image from a bishop, on the canvas.
The problem is, when I instantiate the Bishop
, I don't see any image. So I tried to do the same with a text : instead of using the method create_image from the class Canvas
, I used the method create_text, and it worked : I saw a text on the canvas. That means, the problem comes from the method create_image
, and I don't understand it.
If I create an Image directly in the class GameUi
, it works! but that's not what I want...
So I don't have any error message. I see the canvas (with a blue background), but no image on it.
Here's the code :
from tkinter import PhotoImage, Tk, Canvas
class Pieces:
def __init__(self, can, color, x_position, y_position):
self.color = color
self.x_position = x_position
self.y_position = y_position
class Bishop(Pieces):
def __init__(self, can, color, x_position, y_position):
super().__init__(can, color, x_position, y_position)
if color == "black":
icon_path = 'black_bishop.png'
elif color == "white":
icon_path = 'white_bishop.png'
icon = PhotoImage(file=icon_path) # doesn't see the image
can.create_image(x, y, image=icon)
class GameUI:
def __init__(self):
self.windows = Tk()
self.windows.title("My chess game")
self.windows.geometry("1080x720")
self.windows.minsize(300, 420)
self.can = Canvas(self.windows, width=1000, height=600, bg='skyblue')
icon = PhotoImage(file=icon_path) # here I create the image in this class, and
can.create_image(x, y, image=icon) # we can see it very well
self.bishop = Bishop(self.can, "black", 50, 50)
self.can.pack()
self.windows.mainloop()
app = GameUI()