[Tkinter-discuss] command for dynamic buttons

Cameron Laird Cameron at phaseit.net
Sat Aug 8 01:09:50 CEST 2009


On Fri, Aug 07, 2009 at 07:06:54PM -0300, Guilherme Polo wrote:
			.
			.
			.
> > Hello! I'm making an application with lots of similar buttons. But I can't
> > figure out how to make the command unique for each button. I tried to follow
			.
			.
			.
> I didn't look at the email you pointed, but if the suggestion included
> there maps to the code you posted then the suggestion is wrong.
> 
> import Tkinter
> 
> def test(option):
>     print option
> 
> things = ['a', 'b', 'c', 'd']
> 
> root = Tkinter.Tk()
> 
> for indx, option in enumerate(things):
>     cmd = lambda opt=option: test(opt)
>     btn = Tkinter.Button(text=option, command=cmd)
>     btn.pack(side='left')
> 
> root.mainloop()
> 
> The line you are after is "cmd = lambda opt=option: test(opt)". If
> instead you do "cmd = lambda: test(option)" (which is equivalent to
> what the code you pasted was doing), then when this lambda executes it
> will have to grab the value of this name "option" from somewhere,
> which will be the last element from the things list.
			.
			.
			.
Also, look for "Parameter-passing" in <URL:
http://tkinter.unpy.net/wiki/Widgets/Button >.


More information about the Tkinter-discuss mailing list