我正在創建一個棋盤來顯示我的 NQueensProblem 搜索。我制作了一個網格并用顏色填充了單元格。但是,我不能用“女王圖片”來填補女王的位置。例如,我在 (0, 1) 有一個女王,我希望這個單元格顯示一張女王圖片。請幫我解決一下這個。非常感謝大家!!!

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)
uj5u.com熱心網友回復:
bug將影像分配給函式中的區域變數時PhotoImage洗掉影像是常見問題。您必須使用全域變數或類變數。
請參閱
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455796.html
標籤:Python 图片 tkinter 网格 蟒蛇国际象棋
上一篇:添加影像后,檢查按鈕不可點擊
