在创建它们时在循环内给多个矩形(使用图形模块)不同的名称?

Give multiple rectangles (using the graphics module) different names inside a loop while creating them?

我正在尝试使用图形对 python 中的生活游戏进行编码,但如果不单独创建框,我无法在我创建的网格中给出每个矩形:

from graphics import *  
import tkinter  
import time 

#create a window:   
win = GraphWin('Game Of Life', 600, 600)    
x = 0   
y = 0   

#create a grid:     
for count in range(20): 
    for count in range(20): 
      rect = Rectangle(Point(x, y), Point((x + 20), (y + 20)))  
      rect.setOutline('black')  
      rect.setFill('white') 
      rect.draw(win)    
      x = x + 20    
    x = 0   
    y = y + 20  

#define updating a rectangle:   
def update(a):  
    if a.config["fill"] == "black": 
        a.setFill('white')  
    if a.config["fill"] == "white": 
        a.setFill('black')  

因为您试图在同一个变量中创建所有这些矩形,所以每个新矩形都会覆盖之前的矩形。

您可以尝试将这些矩形添加到列表或其他数据类型中,以便存储。

可能是这样的:

from graphics import *  
import tkinter  
import time 

#list of rectangles
rect = []

#create a window:   
win = GraphWin('Game Of Life', 600, 600)    
x = 0   
y = 0   

#create a grid:     
for count in range(20): 
    for count in range(20): 
      rect.append(Rectangle(Point(x, y), Point((x + 20), (y + 20)))) 
      rect[-1].setOutline('black')  
      rect[-1].setFill('white') 
      rect[-1].draw(win)    
      x = x + 20    
    x = 0   
    y = y + 20  

#define updating a rectangle:   
def update(a):  
    if a.config["fill"] == "black": 
        a.setFill('white')  
    if a.config["fill"] == "white": 
        a.setFill('black') 

矩形被附加到列表中,然后我们使用 rect[-1].

访问它