我正在用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
用作课程的主题(不确定这是否是正确的放置方式),但是它不起作用。我不知道我要尝试的方法是否正确,但是我想在方格中创建“ Pieces”以供检查。如果我在image = black_pieces[-1]
行中将bg = "green"
更改为board[i].config(image = black_pieces[-1], state = NORMAL)
,则正确的正方形将变为绿色背景,因此问题出在图像上(我的图像是黑白的png图像草稿保存在名为black.png和white.png的同一目录中的文件。任何帮助将不胜感激。