Home > Mobile >  Fill in a cell of grid with a picture using Tkinter Python
Fill in a cell of grid with a picture using Tkinter Python

Time:04-03

I am creating a chessboard to display my NQueensProblem search. I have made a grid and filled in the cells with colors. However, I can't fill the positions of queens with 'queen picture'. For example, I have a queen at (0, 1) and I want this cell display a queen picture. Please help me with this. Thank all of you very much!!! enter image description here

    import tkinter as tk
from tkinter.tix import IMAGETEXT
from matplotlib import colors
from PIL import Image, ImageTk

class GUI(tk.Frame) :
    def __init__(self, position, no_of_queens) :
        tk.Frame.__init__(self)
        self.grid()
        self.master.title('Order Queens')

        self.main_grid = tk.Frame(self, bg = '#a39489', bd = 0, width = 50, height = 50)

        self.main_grid.grid(pady = (0, 0))

        self.display_GUI(position, no_of_queens)
        self.mainloop()

    def make_GUI(self, no_of_queens) :
        # make grid
        self.cells = []
        for i in range(no_of_queens) :
            row = []
            for j in range(no_of_queens) :
                if i % 2 == 0 :
                    if j % 2 == 0 :
                        cell_color = '#f2dbbb'
                    else :
                        cell_color = '#832c33'
                else :
                    if j % 2 == 0 :
                        cell_color = '#832c33'
                    else :
                        cell_color = '#f2dbbb'

                cell_frame = tk.Frame(self.main_grid, bg = cell_color, width = 45, height = 45)
                cell_frame.grid(row = i, column = j, padx = 0, pady = 0)
                cell_number = tk.Label(self.main_grid, bg = cell_color)
                cell_number.grid(row = i, column = j)
                cell_data = {'frame': cell_frame, 'number': cell_number}
                row.append(cell_data)

            self.cells.append(row)
        
    def display_GUI(self, position, no_of_queens) :
        self.make_GUI(no_of_queens)

        img = tk.PhotoImage(file = 'C:\Users\Admin\Downloads\queen.gif')
        for i in range(no_of_queens) :
            #label.grid
            self.cells[i][position[i]]['number'].configure(image = img)


if __name__ == '__main__':
    no_of_queens = 8
    position = (1, 2, 3, 0, 5, 7, 4, 6)
    GUI(position, no_of_queens)

CodePudding user response:

It is common problem with bug in PhotoImage which removes image when it is assigned to local variable in function. You have to use global variable or class variable.

See Note at the end of page enter image description here

  • Related