variable name using a for

Peter Otten __peter__ at web.de
Tue Mar 2 15:10:48 EST 2004


Alex wrote:

> Thank you very much for the reply!
> 
> In fact I created a list in a variable and I have to create x numbers of
> butons, depending on how many values there's in the list.
> 
> so in my code:
> for x in range(nbSujets):
>   self.button1 = xbmcgui.ControlButton(50, 100, 40, 30, "B"+str(x) )
>   self.addControl(self.button1)
> 

You have several options:

(1)
for x in range(nbSujets):
    button = xbmcgui.ControlButton(...)
    self.addControl(button)

I don't know that particular gui, but access to the button should be
possible by something like self.getControl(buttonname) or
self.controls[buttonindex] - just look it up in the docs.

(2)
self.buttons = []
for x in range(nbSujets):
    button = xbmcgui.ControlButton(...)
    self.addControl(button)
    self.buttons.append(button)

Refer to the button later as self.buttons[buttonindex]

(3)
for x in range(nbSujets):
    button = xbmcgui.ControlButton(...)
    self.addControl(button)
    setattr(self, "button" + str(x), button)

Refer to the button later as self.button0, self.button1, ...


> But in fact I need self.buttonX as I need different actions on each
> button. And the dictionnary here doesn't help I think...

Perhaps you can find a way to connect buttons and actions directly in the
for loop and need not refer to them later at all?

(4)
for x, action in enumerate([self.killMonster, self.saveTheWorld]):
   button = xbmcgui.ControlButton(...)
   button.onClick = action # speculating again here
   self.addControl(button)

killMonster() and saveTheWorld() are the methods that shall be triggered
when the associated button is pressed.

Incidentally, the last one is my personal favourite.
        
Peter




More information about the Python-list mailing list