[Tutor] Recursive Tkinter buttons
Michael Lange
klappnase at freenet.de
Sun Feb 27 15:38:14 CET 2005
On Sat, 26 Feb 2005 19:48:25 +0000
Adam Cripps <kabads at gmail.com> wrote:
> On Fri, 25 Feb 2005 12:21:18 +0100, Michael Lange
> <snip>
> >
> > You see, in my example above I called the list "buttonlist" instead of "button"; maybe this naming
> > helps avoid confusion .
> >
> > Best regards
> >
> > Michael
>
> Many thanks for the help here.
>
> I got all my buttons displayed and stored in the list with:
>
> for i in range (1, 11):
> submittext = ">>> "
> self.s = Button(text=submittext, command = self.showButton)
> self.s.grid(column=4, row=i+4)
> submitlist.append(self.s)
>
Hi Adam,
note that there's no use in making the button an attribute of its parent class with
self.s = Button(text=submittext, command = self.showButton)
because self.s gets overridden on every iteration in the for-loop; it's not a bug, but
might be a source of confusion, when you try to access self.s later in your code; you don't
need the reference anyway, because you keep the references to all buttons in the list.
>
> - however, when I click the button, I want self.showButton to know
> which one of them was pressed. I've seen in other gui programming the
> idea of an id or identifier - I can't see that here. Ideally, I would
> like to know the value of i in self.showButtons - but when I use
> self.showButtons(i) showButtons gets called straight at run time.
>
> Any ideas?
You have two options here:
1. use a lambda expression as button command, lambda allows you to pass an argument to the callback:
s = Button(text=submittext, command = lambda index=i: self.showButton(index))
2. if you don't like lambdas, you can use the button's bind() method instead of the command option:
s = Button(text=submittext)
s.bind('<ButtonRelease-1>', self.showButton)
s.bind('<KeyRelease-space>', self.showButton)
bind() passes an event to the callback which allows you to find out which widget sent the event via the
event's widget attribute:
def showButton(self, event):
button = event.widget
print button['text']
I hope this helps
Michael
More information about the Tutor
mailing list