
"""Buttons2  shows how to construct a customized event-handling function for
   each button in a GUI by using a _function that returns a function as its answer_.
"""
from Tkinter import *

HOW_MANY = 8  # how many buttons we place into the GUI


# THE ``MODEL'' (DATA STRUCTURE) FOR THIS DEMO  --- IT USUALLY
#  LIVES IN A SEPARATE MODULE:

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
        but.configure(text=all_counts[location])

    return handlePress  # return the  handlePress function, customized by
                        # to the values of  but  and  location


myfont = ("Arial", 16, "bold")
window = Tk()
window.title("counters")

width = HOW_MANY * 100
window.geometry(str(width) + "x120")

frame = Frame(window)
frame.grid()

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)
    # connect the new handler function to the new button:
    new_button.configure(command = new_handler)

window.mainloop()
