我想用OOP创建一个国际象棋程序。所以我创建了一个超类Pieces
,一个子类Bishop
,和一个UI类GameUI
。我在GameUI类中创建了一个画布。我想,当我在类GameUI
中实例化一个对象bishop时,它会在画布上显示一个bishop的图像
问题是,当我实例化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()
为了使代码正常工作,我决定基于this answer重写它。它现在可以工作了,但实际上您需要添加的唯一内容是
self.icon
,而不是icon
icon
获取垃圾回收,因为没有对它的进一步引用,而self.icon
仍然存在。而且,它和你的不完全一样,所以可能也需要重写一下相关问题 更多 >
编程相关推荐