[Tkinter-discuss] creating widgets generically, with a loop?

Martin Franklin mfranklin1 at gatwick.westerngeco.slb.com
Wed Jun 21 11:13:54 CEST 2006


Mike Steiner wrote:
> Some background info: I have a Python/Tkinter script that displays a
> dialog with buttons, where each button launches a file for editing.
> Sort of like an HTML file in a browser, except with my script I can
> launch it using a particular program.
> 
> I've been trying to figure out a way of storing widget information
> (name of each widget, x and y positions, and a command to execute
> when activated) in an array so I can generically create each widget
> instead of hard-coding all the information. For example, here's a
> snippet of what I currently use:
> 
>     ...
>     Button(top, text="OO design info",
> command=self.launch_file23).grid(sticky="w",row=10,column=5)
>     ...
> 
>     ...
>     def launch_file23 ( self ): os.spawnl ( os.P_NOWAIT , 
> "c:\\Program Files\\TextPad 4\\TextPad.exe" , "TextPad.exe" , "d:\\My
> 
> 
> Documents\\prog_oo_design.txt" )
>     ...
> 
> If there was a way I could pass arguments to launch_file23 from the
> "command=" parameter, that would solve the problem nicely - I could
> store the info in an array, and then just loop to create the buttons.
> 
> Any ideas?
> 

Perhaps:


my_buttons = [
## fullpath names should be used here but for the sake of wrapping
   ("OO design info", "TextPad.exe", "oo_design.txt"),
   ("AA design info", "TextPad.exe", "aa_design.txt"),
   ("ZZ design info", "TextPad.exe", "zz_design.txt"),
]


def launchit(external, filename):
   external_short = os.path.split()[1]
   def real_launchitit():
       os.spawnl(os.P_NOWAIT, external, external_short, filename)
   return real_launchit

for text, external, filename in my_buttons:
   b = Button(self, text=text, command=self.launchit(external, filename))
   b.grid()

























More information about the Tkinter-discuss mailing list