尽管存在参考,Tkinter 按钮不显示图像

Tkinter button not displaying image despite existing reference

我在 Python 中使用 tkinter 创建的基于 GUI 的国际象棋游戏中,我使用图像在网格按钮上显示棋子。图像 .png 文件位于与程序相同的目录中的文件夹中。当我 运行 代码时,图像不会显示在按钮上。我发现 this question 说我需要保留变量的引用。我的代码保留了一个引用,尽管图像不显示。 (请记住,目前图像只会显示黑色棋子)

这是创建按钮的代码 (Python 3.7):

class Space(tk.Button):
color = 0
inst_num = 0

def __init__(self, name, root, player=None):
    Space.inst_num += 1
    Space.color += 1
    Space.color += (1 if Space.color % 9 == 0 else 0)

    self.root = root
    self.name = name
    self.player = player

    super().__init__(self.root, image=P_ABBREVIATIONS[self.name], bg=('grey' if Space.color % 2 == 0 else 'white'),
                     fg=('black' if player == 'B' else 'grey22'), height=80, width=80, relief='flat')

这里是存储 PhotoImage 对象的代码:

if __name__ == '__main__':
    master = tk.Tk()

P_ABBREVIATIONS = {'Pawn': tk.PhotoImage(r'icons\b_pawn.png').subsample(8, 8)}      # For now only Pawn TODO: add other chess peice PhotoImage objects 

if __name__ == '__main__':
    Chess = ChessBoard(master)
    master.mainloop()

完整代码请访问: https://pastebin.com/JXxBsLCz

问题是您创建的图像不正确。路径需要分配给 file 选项。第一个位置参数被指定为图像的内部名称。因此,如果您省略 file=,您将指定一个名称,但不会为图像提供任何数据。

tk.PhotoImage(file=r'icons\b_pawn.png')
              ^^^^^