Re: Tkinter problem

Guido.van.Rossum@cwi.nl
Thu, 19 Jan 1995 12:35:42 +0100

> While translating some code from Tcl/Tk to python/tkinter I've found a
> piece of code I can't figure out how to write in python. In particular:
>
> foreach i {1 2 3 4 5} {
> button .$i -text "$i" -command "puts $i"
> pack .$i -side left
> }
>
> In this code I use information available at the time the buttons
> are created ($i), that won't be available when the button is pushed
> if I wanted to used a callback (like I think I have to in
> python).

In Python, you would probably create a list of buttons. What you can
do is assign the button number to an instance attribute of each
button, e.g. (untested, but you get the gist):

buttons = []
for i in range(5):
buttons[i] = b = Button(master, {'text': `i`, 'command': b_callback})
b.my_number = i

I believe the callback function receives its widget as a parameter so
the b_callback function will be able to figure out its button number.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>