Tkinter按钮尽管已有参考也没有显示图像

问题描述 投票:-1回答:1

[在我使用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

python tkinter python-3.7 chess python-chess
1个回答
0
投票
tk.PhotoImage(file=r'icons\b_pawn.png') ^^^^^
© www.soinside.com 2019 - 2024. All rights reserved.