I'm coming today with a really big issue that I can't solve :
I'm trying to make a chess game in python, with a Tkinter GUI, so I need to create a grid of 8 by 8 buttons which contains images. The thing is that when I put images in, the buttons are not clickable anymore and the images don't even show up. I asked many people but none of them know how to solve my issue.
Here is the code :
import chess
import tkinter as tk
from PIL import ImageTk, Image
class Button:
def __init__(self,master,x,y,image):
self.content = tk.Button(master,image=image,height=40,width=40,command = lambda : click_square(x,y))
def click_square(x,y):
print('x = ',x,', y = ',y)
win = tk.Tk()
win.geometry('440x440')
frame = tk.Frame(win,bg='green',padx=40,pady=40)
frame.pack(fill=tk.BOTH, expand=tk.YES)
class TkBoard():
def __init__(self):
self.board = [[piece for piece in board_row.split(' ')] for board_row in [row for row in str(chess.Board()).split('\n')]]
#print(self.board)
dico_img = images()
for i in range(8):
for j in range(8):
button = Button(frame,i,j,dico_img[self.board[i][j]])
print(dico_img[self.board[i][j]])
button.content.grid(row=i,column=j)
def images():
dico = {'r':'br','R':'wr','n':'bn','N':'wn','b':'bb','B':'wb','q':'bq','Q':'wq','k':'bk','K':'wk','p':'bp','P':'wp','.':'blank'}
dico_img = {}
for key in dico.keys():
location = 'images/'+dico[key]+'.png'
img = Image.open(location)
img = img.resize((40,40))
image = ImageTk.PhotoImage(img)
dico_img[key] = image
return dico_img
def without_png(piece):
return piece[:-4]
TkBoard()
win.mainloop()
I put all of the images in an affiliate folder called "images". Here is the download link.