0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Just to be clear, you're saying if you don't add an image to the button but leave everything else exactly as-is with the code in the question, the buttons work? – Bryan Oakley May 31 '22 at 20:05
  • yes that's exactly it, when i add a button with no image it works, you can try it but replacing the image content in the button by "None" (the button will have a weird shape but it dont really matter) – Jonas Barth May 31 '22 at 21:16
  • I copied and past the function code into my class TkBoard, but it's still not working – Jonas Barth May 31 '22 at 22:53
  • 2
    Try adding `self.content.image = image` at the end of `Button.__init__()` to save the reference of the image. – acw1668 May 31 '22 at 23:56
  • The code in your question is not a [mre] because the definition of the `chess` module is missing. Specifically `chess.Board()` is undefined. – martineau Jun 01 '22 at 00:15
  • 1
    Doing as @acw1668 suggests will fix the problem. – martineau Jun 01 '22 at 01:16

0 Answers0