
"""Counters3  shows how to remember the addresses of all the button
   objects so that the press of one button can affect all the others.
"""
from Tkinter import *

HOW_MANY = 8                 # how many buttons we place into the GUI
all_counts = HOW_MANY * [0]  # a list of counts for all the buttons

def constructHandler(but, location) :
    """constructs a custom event-handling function for a GUI button.

       parameters:  but - a button object, the button just constructed
              that requires its own event-handling function
          location - the position of the button on the GUI and the
              position of the button's count in the  all_counts  list
    """
    def handlePress() :
        """is called when the button,  but,  is pressed: it increases 
           the count for  but  and updates the text on  but's  face
        """
        global all_counts
        all_counts[location] = all_counts[location] + 1

        erase_all_buttons()  # call helper function to erase everyone

        but.configure(text = all_counts[location])  # redisplay count

    return handlePress  

def erase_all_buttons() :
    """resets the text of all the buttons to blanks"""
    global all_buttons
    for but in all_buttons :
        but.configure(text = " ")


####THE VIEW (GUI) PART STARTS HERE:

myfont = ("Arial", 16, "bold")
window = Tk()
window.title("counters")

width = HOW_MANY * 100
window.geometry(str(width) + "x120")

frame = Frame(window)
frame.grid()

all_buttons = [] # remembers the addresses of all the button objects

for i in range(HOW_MANY) :

    new_button = Button(frame, font = myfont, text = 0,
                    fg = "blue", bg = "white", width = 4, height = 2)
    new_button.grid(row = 1, column = i, padx = 10, pady = 10 )

    new_handler = constructHandler(new_button,i)
    new_button.configure(command = new_handler)

    all_buttons = all_buttons + [new_button] # remember the new button

window.mainloop()


