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']
我知道这不是正确的订单,但我只想立即将其显示在板上。
我期望在顶部2和底部2行。]的每个正方形上得到碎片。
- 为什么不是这种情况?
- 还有为什么车子被黑匣子包围?我的图片没有那个框。
使用@Boendal答案,我得到以下信息:
为什么某些正方形的中心有黑色正方形(特别是件在哪里)?
编辑#2:
黑色正方形是由于图像不透明。
通过使用here找到的信息将它们转换为透明来解决
[代码:导入tkinter,从PIL导入os,导入ImageTk,图像def sortFileImages(文件):black = [如果i中为'black',则i为文件中的i,i = white = [i中i为'white',i为文件中的i,对于i,i]典当= [[i] * 7 ...
您所缺少的是保留图像的引用。
label = tkinter.Label(root, image=img, borderwidth=8)
label.image=img