[Tutor] Functions and random buttons

Alan Gauld alan.gauld at freenet.co.uk
Tue Mar 7 10:42:00 CET 2006


Simon,

> ...I want to make each button clickable

The buttons are clickable so I'm not absolutely sure what you mean?
Do you mean you want to add some action to them when they are clicked?
Thats done with the command option in Tkinter.

define a function and assign it to the button.

In this case it will likely be the same function for all buttons so you 
might
want to do a wee bit of trickery like:

def func(x,y):    #x,y the button coords
    # do something here

        for i in range(length):
            for j in range(length):
                self.dict['%s%s' % (i, j)] = Button(sel.frame, text = ' 
'
                                                         command = lambda 
x=i,y=j: func(x,y))

That uses the default values of the lambda function to pass the coords
of the button being pressed to your generic function. func can then use
those coords to address the button in the dictionary to update the label
or appearance etc.

One other wee point:

                self.dict['%s%s' % (i, j)].grid(row = i, column = j)

You don't need to use a string for a key in a dictionary, the tuple will be
just fine so you can replace the string formatting stuff with:

                self.dict[(i, j)].grid(row = i, column = j)

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list