From: Andy T. <an...@ha...> - 2006-12-19 07:30:40
|
Alex Tweedly wrote: > Alec Bennett wrote: >> This is a hard one to explain, but here goes. I'd like to be able to >> script component names in my PythonCard layout. >> >> For example, instead of saying something like: >> >> self.components.button4.file = "some_picture.jpg" >> >> I'd like to be able to do something like: >> >> button_number = 4 >> button = 'self.components.button" + `button_number` + ".file = >> "some_picture.jpg"' >> >> Currently I'm burying everything in way too many if statements, which >> is always a sign I'm doing things sloppily. If I could write a >> function that, for example, redraws only a specific button, my code >> would get much neater. But without being able to script or concatenate >> the component name, I can't think of a way to do that. >> >> Is such a thing possible? Or is there some clever way to achieve the same thing? > As Ed says, you could use Python's 'exec' - but that always feels a > bit like cheating to me :-) > > In Pythoncard, you can refer to components as either > self.components.button4 > or > self.components["button4"] > > so I'd do something like > > button_name = "button%d" % button_number > self.components[button_name].file = "something.jpg" > > > > > -- > > Alex Tweedly mailto:al...@tw... www.tweedly.net > And you should be able to check that the object exists before referencing it by using hasattr, e.g. (not tested so apologies for syntax errors); >>> button_name = 'button' + passed_in_value >>> if hasattr(self.components, button_name): ... self.components[button_name] = 'something.jpg' For a case study of how to write code without referring to widgets by name take a look at the dbBrowser sample application. That creates and modifies components at run time. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ |