我想使用 OOP 创建一个国际象棋程序。所以我创建了一个超类 Pieces
、一个子类 Bishop
和一个 UI 类 GameUI
。我在类 GameUI 中创建了一个画布。我希望,当我在类 GameUI
中实例化一个对象主教时,它会在画布上显示来自主教的图像。
问题是,当我实例化 Bishop
时,我看不到任何图像。所以我尝试对文本做同样的事情:我没有使用类 Canvas
中的 create_image 方法,而是使用了 create_text 方法,它起作用了:我在画布上看到了一个文本。这意味着,问题来自方法 create_image
,我不明白。
如果我直接在类 GameUi
中创建图像,它会起作用!但这不是我想要的...
所以我没有任何错误信息。我看到画布(蓝色背景),但上面没有图像。
代码如下:
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()
答案 0 :(得分:0)
为了使您的代码正常工作,我决定根据 this answer 对其进行某种程度的重写。它现在可以工作了,但实际上您唯一需要添加的是 self.icon
而不是 icon
。 icon
被垃圾回收,因为没有进一步引用它,而 self.icon
仍然存在。此外,它与您的并不完全相同,因此它可能也需要一些重写。
from tkinter import *
from random import randint
class Piece:
def __init__(self, canvas, x1, y1):
self.x1 = x1
self.y1 = y1
self.canvas = canvas
class Bishop(Piece):
def __init__(self, canvas, x1, y1, color):
super().__init__(canvas, x1, y1)
if color == "black":
icon_path = 'black_bishop.png'
elif color == "white":
icon_path = 'white_bishop.png'
self.icon = PhotoImage(file=icon_path)
self.ball = canvas.create_image(self.x1, self.y1, image=self.icon)
def move_piece(self):
deltax = randint(0,5)
deltay = randint(0,5)
self.canvas.move(self.ball, deltax, deltay)
self.canvas.after(50, self.move_piece)
class GameUI:
def __init__(self):
# initialize root Window and canvas
root = Tk()
root.title("Chess")
root.resizable(False,False)
canvas = Canvas(root, width = 300, height = 300)
canvas.pack()
# create two ball objects and animate them
bishop1 = Bishop(canvas, 10, 10, 'white')
bishop2 = Bishop(canvas, 60, 60, 'black')
bishop1.move_piece()
bishop2.move_piece()
root.mainloop()
app = GameUI()