【发布时间】:2021-08-25 06:22:33
【问题描述】:
我想使用 OOP 创建一个国际象棋程序。所以我做了一个超类Pieces,一个子类Bishop,和一个UI类GameUI。我在 GameUI 类中创建了一个画布。我想要,当我在 GameUI 类中实例化一个对象 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()
【问题讨论】:
-
尝试使用
self.icon -
GameUI.__init__中的代码不等于Bishop.__init__中的代码。使用 GameUI.__init__ 中的隐式值比较结果:file='black_bishop.png'、x=50、y=50
标签: python image oop tkinter canvas