如何制作一个由矩形组成的网格,以便每个矩形都可以在代码中使用其位置(行和列的元组)进一步使用?

How to make a grid consisting of rectangles so that each rectangle can be used further in the code using its position (a tuple of row and column)?

我有这个:

from tkinter import *
import numpy as np
rows = 10
columns = 10

width, height = rows*18, columns*18
window = Tk()
window.geometry(str(width)+"x"+str(height))
window.resizable(width=False, height=False)
window.config(background="#A9A9A9")

field_frame = Frame(width=width, height=height, bg="#A9A9A9", colormap="new")
field_frame.pack(side=BOTTOM)
field_frame.grid_propagate(False)

pixelVirtual = PhotoImage(width=1, height=1) #To measure the size in pixels

btnarr = np.zeros(shape=(rows, columns), dtype=object)

def button_click(row, column):
    #<SOME CODE HERE>
    pass
def placebuttons(rows=rows, columns=columns):
    for row in range(rows):
        for column in range(columns):
            btnarr[row, column] = (Button(field_frame, text="", image=pixelVirtual, height = 12, width = 12, command=lambda row=row, column=column:[(button_click(row, column)), btnarr[row,column].place_forget()]))
            btnarr[row, column].place(x=column*18, y=row*18)
placebuttons()

window.mainloop()

我也想这样做,但使用 pygame 和矩形而不是按钮。但是我还没有在 Internet 上的任何地方找到如何创建矩形网格,以便可以通过 array[row, column] 或 array(row, column) 访问它们。请帮忙

这是在 pygame 中创建 Rect 网格的示例。有关其工作原理的更多说明,请参阅评论。

import pygame

import numpy as np
from random import randint
from pygame.constants import *
#define main constants, edit to change window and rect formats
rows=10
columns=10

rectwidth,rectheight=50,50
width,height=rows*rectwidth,columns*rectwidth
#create window and initialise pygame
pygame.init()
screen= pygame.display.set_mode((width,height))
#fill window
bg=pygame.Surface((width,height))
bg.fill("#A9A9A9")
screen.blit(bg,(0,0))
#create btnArr
btnArr=np.zeros(shape=(rows, columns), dtype=object)
def placebuttons(rows=rows, columns=columns):
    for row in range(rows):
        for column in range(columns):
            #create a rect placed on the right place
            btnArr[row, column] = pygame.Rect((row*rectwidth,column*rectheight),(rectwidth,rectheight))
placebuttons()
surf=pygame.Surface((rectwidth,rectheight))
surf.fill((0,0,0))
running=True
while running:
    #notice wether user closed the window
    for event in pygame.event.get():
        if event.type==QUIT:
            
            running=False
    #reset window
    screen.blit(bg,(0,0))
    #place surfaces here, see example
    screen.blit(surf,btnArr[1,1])
    pygame.display.flip()
# main loop finished, time to quit
pygame.quit()