DitoOgiashvili
DitoOgiashvili

Reputation: 41

creating statictext dynamically and then setting label with python

I'm creating table with static text with a while loop, after that I want to set labels. I'm having problem with it, because it only works with the last one. Here is my code:

import wx

class Mainframe(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.panel = wx.Panel(self)

        def test(self,n):
            while n <=5:
                a = wx.StaticText(self.panel, label='bad', id=n, pos=(20,30*n))
                n = n+1
            return a

        test(self,0)

        if test(self,0).GetId()==1:
            test(self,0).SetLabel('good')

        if test(self,0).GetId()==5:
            test(self,0).SetLabel('exelent')

if __name__=='__main__':
    app = wx.App(False)
    frame = Mainframe(None)
    frame.Show()
    app.MainLoop()

Upvotes: 0

Views: 563

Answers (1)

Yoriz
Yoriz

Reputation: 3625

When you are returning a it is only the last control created because each time you loop it is overwritten. Append the controls to a list and then you can access them all. Also note that you are calling test 5 times, so you will have 5 lots of your set of statictexts created on top of each other.

import wx


class Mainframe(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.panel = wx.Panel(self)

        ctrls = []
        for n in range(6):
            ctrls.append(wx.StaticText(self.panel, label='bad',
                pos=(20, 30 * n)))

        ctrls[1].SetLabel('good')
        ctrls[5].SetLabel('excellent')


if __name__ == '__main__':
    app = wx.App(False)
    frame = Mainframe(None)
    frame.Show()
    app.MainLoop()

Upvotes: 1

Related Questions