棋盘上的棋子不会显示

时间:2019-12-14 03:10:50

标签: python python-3.x tkinter python-chess

代码:

import tkinter, os
from PIL import ImageTk, Image

def sortFileImages(files):
    black = [i for i in files if 'black' in i]
    white = [i for i in files if 'white' in i]
    pawns = [[i]*7 for i in files if 'pawn' in i]
    return black + pawns[0] + [' ']*32 + pawns[1] + white

files = sortFileImages(files=os.listdir("web/images/"))
root = tkinter.Tk()

index = 0
for r in range(8):
    for c in range(8):
        if files[index] != ' ':
            img = ImageTk.PhotoImage(Image.open('web/images/{}'.format(files[index])).resize((64,64)))
        else:
            img = ImageTk.PhotoImage(Image.new('RGB', (64,64)))
        label = tkinter.Label(root, image=img, borderwidth=8)

        # Color the grid squares
        if (r%2 == 0 and c%2 == 0) or (r%2 == 1 and c%2 == 1):
            label.configure(background='grey')
        else:
            label.configure(background='white')

        label.grid(row=r,column=c)
        index += 1

root.mainloop()

变量值:

  

files

['black-bishop.png', 'black-bishop2.png', 'black-king.png', 'black-knight.png', 'black-knight2.png', 'black-pawn.png', 'black-queen.png', 'black-rook.png', 'black-rook2.png', 'black-pawn.png', 'black-pawn.png', 'black-pawn.png', 'black-pawn.png', 'black-pawn.png', 'black-pawn.png', 'black-pawn.png', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'white-pawn.png', 'white-pawn.png', 'white-pawn.png', 'white-pawn.png', 'white-pawn.png', 'white-pawn.png', 'white-pawn.png', 'white-bishop.png', 'white-bishop2.png', 'white-king.png', 'white-knight.png', 'white-knight2.png', 'white-pawn.png', 'white-queen.png', 'white-rook.png', 'white-rook2.png']

我知道这不是正确的订单,但我只想立即将其显示在板上。

输出:

Chess board output I am getting

问题:

  

我希望在顶部2 底部2行的每个正方形上得到碎片。

  1. 为什么不是这样?
  2. 为什么车子被黑匣子包围?我的图片没有那个框。

编辑:

使用@Boendal答案,我得到以下信息:

new board with a few missing pieces

  

为什么某些正方形的中心有黑色正方形(尤其是   碎片在哪里)?

编辑#2:

黑色正方形是由于图像不透明所致。

通过使用here找到的信息将其转换为透明,从而解决了该问题

1 个答案:

答案 0 :(得分:1)

您缺少的是保留图像的引用。

label = tkinter.Label(root, image=img, borderwidth=8)
label.image=img

应该解决问题。您也可以替换if

if (r%2 == 0 and c%2 == 0) or (r%2 == 1 and c%2 == 1):

使用

if r%2 == c%2:

参考: http://effbot.org/tkinterbook/photoimage.htm

@编辑黑色背景:

如果我使用您的代码,则整个面板上都有黑色正方形,但没有图像。如果我使用以下代码(对我而言,它将始终进入else部分):

if files[index] != ' ':
    img = ImageTk.PhotoImage(Image.open('web/images/{}'.format(files[index])).resize((64,64)))
    label = tkinter.Label(root, image=img, borderwidth=8)
    label.image = img
else: # Always jump into else because my files is filled with ' '
    label = tkinter.Label(root, image='web/images/{}'.format("blank.png"), borderwidth=8)

为此,我用64x64完全透明的图像填充空白字段。它对我来说很好,没有奇怪的大小,没有黑色方块

您需要一幅全透明64x64的图像。用photoshop或gimp创建一个。

关于这些数字后面的黑色方块,我认为这些数字有问题(黑卒和高塔)。