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

Question:

I’m trying to code the game of life in python using graphics, but I can’t give each rectangle in the grid I’ve created without creating the boxes individually:

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')  
Asked By: Otto Moir

||

Answers:

Because you are trying to create all those rectangles in the same variable, so every new rectangle overwrites previous one.

You could try to add those rectangles to a list or other datatype, for it to be stored.

Maybe something like this:

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') 

Rectangles are getting appended to the list, then we access it by using rect[-1].

Answered By: Wankiet
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.