[Tkinter-discuss] creating widgets generically, with a loop?
Mike Steiner
mikejaysteiner at yahoo.com
Thu Jun 22 18:00:52 CEST 2006
It works!
Thanks for your help. I've included the complete (it's small) source
file below, in case anyone's curious.
----- start of .py file -----
import os
from Tkinter import *
class App:
def __init__( self , top ):
top.geometry ( "+0+0" )
my_buttons = [ ( "button_text1" , "program_name1" ,
"file_name1" , 1 , 0 ) , ( "button_text2" , "program_name2" ,
"file_name2" , 0 , 1 ) ]
for text , external , filename , row , col in my_buttons:
b = Button( top , font=("Verdana",7) , pady=0 ,
borderwidth=0 , text=text , command=self.launchit(external,filename)
)
b.grid( sticky="w" , row=row , column=col )
## this function is called when you create the Button widget
def launchit ( self , external , filename ):
external_short = os.path.split( external )[1]
## this inner function has access to the outer functions
## namespace
def real_launchit ( ):
os.spawnl ( os.P_NOWAIT , external , external_short ,
filename )
## return a reference to the inner function
## this 'reference to a function' will be called when the
button
## is pressed
return real_launchit
root = Tk()
app = App(root)
root.mainloop()
----- end of .py file -----
--- Martin Franklin <mfranklin1 at gatwick.westerngeco.slb.com> wrote:
> Mike Steiner wrote:
> > Does this work - does the "command=" parameter allow the function
> > value to contain parameters too? If so, it would solve the
> problem
> > easily!
> >
> > --- Martin Franklin <mfranklin1 at gatwick.westerngeco.slb.com>
> wrote:
> >> [ stuff omitted ]
> >> for text, external, filename in my_buttons:
> >> b = Button(self, text=text, command=self.launchit(external,
> >> filename))
> >> b.grid()
> >
>
>
> Mike,
>
>
> Sorry I should have provided some doc strings ;) The magic in my
> example is here:-
>
> ## this function is called when you create the Button widget
> def launchit(external, filename):
> external_short = os.path.split()[1]
>
> ## this inner function has access to the outer functions
> ## namespace
> def real_launchit():
> os.spawnl(os.P_NOWAIT, external, external_short, filename)
>
> ## return a reference to the inner function
> ## this 'reference to a function' will be called when the
> button
> ## is pressed
> return real_launchit
>
>
> on re-reading the example I noticed I had made a couple of typoes
>
> Cheers
> Martin
>
>
>
> _______________________________________________
> Tkinter-discuss mailing list
> Tkinter-discuss at python.org
> http://mail.python.org/mailman/listinfo/tkinter-discuss
>
Michael Steiner
MikeJaySteiner at yahoo.com
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
More information about the Tkinter-discuss
mailing list