Re: Tkinter problem

Benny Rochwerger (brochwer@legent.com)
Thu, 19 Jan 95 11:27:36 EST

Guido van Rossum writes:
> > 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>

Actually, when the buttons are included in some other widgets (as is
likely the case) the callback will not receive the button as a widget
but instead it will receive its master. I managed to get this working
by subclassing Button:

from Tkinter import *

class HButton(Button):

def callback(self):
print self.i

class app(Frame):

def __init__(self, master=None):

Frame.__init__(self, master)
self.pack()

self.buttons = []

for i in range(5):
self.buttons.append(HButton(self, {'text' : `i`}))
self.buttons[i]['command'] = self.buttons[i].callback
self.buttons[i].i = i
self.buttons[i].pack({"side" : "left"})

a = app()
a.mainloop()

Although this does the job, the simplicity of the Tcl version is
appealing, it looks like using lambda functions the same could be
achieved in python (just an idea).

Thanks for the suggestion ...

Benny