首页 > 解决方案 > 如何在课程中使用 tkinter PhotoImage?

问题描述

我正在用 python 制作一个草稿/跳棋游戏,我有一个问题,我在创建棋子时找不到在线解决方案。我的代码如下:

from tkinter import *

board = []

white_pieces = []
black_pieces = []

class GUI(Frame):
    def __init__(self, master = None):
        self.game_board()

    def game_board(self):
        for y in range(8):
            for x in range(8):
                board.append(Button(root, width = 4, height = 2, bg = "#000000" if (x % 2 == 0 and y % 2 != 0) or (y % 2 == 0 and x % 2 != 0) else "#FFFFFF", state = DISABLED))
                board[-1].grid(row = y + 1, column = x + 1, sticky = N+E+S+W)
                root.rowconfigure(x+1, weight = 1)
                root.columnconfigure(y+1, weight = 1)

        for i in range(8):
            Label(root, bg = "#C9C9C9", text = i+1).grid(row = 0, column = i+1, sticky = N+E+S+W)
            root.rowconfigure(i, weight = 1)

        for i in range(8):
            Label(root, width = 2, bg = "#C9C9C9", text = chr(i+97).title()).grid(row = i+1, column = 0, sticky = N+E+S+W)
            root.columnconfigure(i, weight = 1)


class piece(PhotoImage):
    def __init__(self, position, master = None):
        self.name = "white.png"
        self.position = position


if __name__ == "__main__":
    root = Tk()
    root.title("Draughts")
    window = GUI(root)
    black = PhotoImage("black.png")
    white = PhotoImage("white.png")
    for i in range(24):
        if ((i % 8) % 2 == 0 and (i // 8) % 2 != 0) or ((i % 8) % 2 != 0 and (i // 8) % 2 == 0):
            black_pieces.append(piece([i // 8, i % 8],black))
            board[i].config(image = black_pieces[-1], state = NORMAL)
        else:
            i += 40
            if ((i % 8) % 2 == 0 and (i // 8) % 2 != 0) or ((i % 8) % 2 != 0 and (i // 8) % 2 == 0):
                white_pieces.append(piece([i // 8, i % 8],black))
                board[i].config(image = white_pieces[-1], state = NORMAL)
    root.mainloop()

我正在尝试PhotoImage用作课程的主题(不确定这是否是正确的表达方式),但它不起作用。我不知道我正在尝试的方法是否正确,但我想在需要它们用于跳棋的方块中创建“棋子”。如果我将行中的更改image = black_pieces[-1]bg = "green"board[i].config(image = black_pieces[-1], state = NORMAL),那么正确的方块会得到绿色背景,所以问题在于图像(我有黑白草稿的 png 图像保存在名为 black.png 和 white.png 的同一目录中)。任何帮助将不胜感激。

标签: pythonpython-3.xtkinter

解决方案


推荐阅读